/*
 * jQuery JavaScript Library v1.3.2
 * http://jquery.com/
 *
 * Copyright (c) 2009 John Resig
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
 * Revision: 6246
 */
(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});
/*
 * Sizzle CSS Selector Engine - v0.9.3
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML='   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})();
/*
 * jQuery UI 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
jQuery.ui||(function(c){var i=c.fn.remove,d=c.browser.mozilla&&(parseFloat(c.browser.version)<1.9);c.ui={version:"1.7.2",plugin:{add:function(k,l,n){var m=c.ui[k].prototype;for(var j in n){m.plugins[j]=m.plugins[j]||[];m.plugins[j].push([l,n[j]])}},call:function(j,l,k){var n=j.plugins[l];if(!n||!j.element[0].parentNode){return}for(var m=0;m<n.length;m++){if(j.options[n[m][0]]){n[m][1].apply(j.element,k)}}}},contains:function(k,j){return document.compareDocumentPosition?k.compareDocumentPosition(j)&16:k!==j&&k.contains(j)},hasScroll:function(m,k){if(c(m).css("overflow")=="hidden"){return false}var j=(k&&k=="left")?"scrollLeft":"scrollTop",l=false;if(m[j]>0){return true}m[j]=1;l=(m[j]>0);m[j]=0;return l},isOverAxis:function(k,j,l){return(k>j)&&(k<(j+l))},isOver:function(o,k,n,m,j,l){return c.ui.isOverAxis(o,n,j)&&c.ui.isOverAxis(k,m,l)},keyCode:{BACKSPACE:8,CAPS_LOCK:20,COMMA:188,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38}};if(d){var f=c.attr,e=c.fn.removeAttr,h="http://www.w3.org/2005/07/aaa",a=/^aria-/,b=/^wairole:/;c.attr=function(k,j,l){var m=l!==undefined;return(j=="role"?(m?f.call(this,k,j,"wairole:"+l):(f.apply(this,arguments)||"").replace(b,"")):(a.test(j)?(m?k.setAttributeNS(h,j.replace(a,"aaa:"),l):f.call(this,k,j.replace(a,"aaa:"))):f.apply(this,arguments)))};c.fn.removeAttr=function(j){return(a.test(j)?this.each(function(){this.removeAttributeNS(h,j.replace(a,""))}):e.call(this,j))}}c.fn.extend({remove:function(){c("*",this).add(this).each(function(){c(this).triggerHandler("remove")});return i.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","").unbind("selectstart.ui")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect","none").bind("selectstart.ui",function(){return false})},scrollParent:function(){var j;if((c.browser.msie&&(/(static|relative)/).test(this.css("position")))||(/absolute/).test(this.css("position"))){j=this.parents().filter(function(){return(/(relative|absolute|fixed)/).test(c.curCSS(this,"position",1))&&(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}else{j=this.parents().filter(function(){return(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}return(/fixed/).test(this.css("position"))||!j.length?c(document):j}});c.extend(c.expr[":"],{data:function(l,k,j){return !!c.data(l,j[3])},focusable:function(k){var l=k.nodeName.toLowerCase(),j=c.attr(k,"tabindex");return(/input|select|textarea|button|object/.test(l)?!k.disabled:"a"==l||"area"==l?k.href||!isNaN(j):!isNaN(j))&&!c(k)["area"==l?"parents":"closest"](":hidden").length},tabbable:function(k){var j=c.attr(k,"tabindex");return(isNaN(j)||j>=0)&&c(k).is(":focusable")}});function g(m,n,o,l){function k(q){var p=c[m][n][q]||[];return(typeof p=="string"?p.split(/,?\s+/):p)}var j=k("getter");if(l.length==1&&typeof l[0]=="string"){j=j.concat(k("getterSetter"))}return(c.inArray(o,j)!=-1)}c.widget=function(k,j){var l=k.split(".")[0];k=k.split(".")[1];c.fn[k]=function(p){var n=(typeof p=="string"),o=Array.prototype.slice.call(arguments,1);if(n&&p.substring(0,1)=="_"){return this}if(n&&g(l,k,p,o)){var m=c.data(this[0],k);return(m?m[p].apply(m,o):undefined)}return this.each(function(){var q=c.data(this,k);(!q&&!n&&c.data(this,k,new c[l][k](this,p))._init());(q&&n&&c.isFunction(q[p])&&q[p].apply(q,o))})};c[l]=c[l]||{};c[l][k]=function(o,n){var m=this;this.namespace=l;this.widgetName=k;this.widgetEventPrefix=c[l][k].eventPrefix||k;this.widgetBaseClass=l+"-"+k;this.options=c.extend({},c.widget.defaults,c[l][k].defaults,c.metadata&&c.metadata.get(o)[k],n);this.element=c(o).bind("setData."+k,function(q,p,r){if(q.target==o){return m._setData(p,r)}}).bind("getData."+k,function(q,p){if(q.target==o){return m._getData(p)}}).bind("remove",function(){return m.destroy()})};c[l][k].prototype=c.extend({},c.widget.prototype,j);c[l][k].getterSetter="option"};c.widget.prototype={_init:function(){},destroy:function(){this.element.removeData(this.widgetName).removeClass(this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").removeAttr("aria-disabled")},option:function(l,m){var k=l,j=this;if(typeof l=="string"){if(m===undefined){return this._getData(l)}k={};k[l]=m}c.each(k,function(n,o){j._setData(n,o)})},_getData:function(j){return this.options[j]},_setData:function(j,k){this.options[j]=k;if(j=="disabled"){this.element[k?"addClass":"removeClass"](this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").attr("aria-disabled",k)}},enable:function(){this._setData("disabled",false)},disable:function(){this._setData("disabled",true)},_trigger:function(l,m,n){var p=this.options[l],j=(l==this.widgetEventPrefix?l:this.widgetEventPrefix+l);m=c.Event(m);m.type=j;if(m.originalEvent){for(var k=c.event.props.length,o;k;){o=c.event.props[--k];m[o]=m.originalEvent[o]}}this.element.trigger(m,n);return !(c.isFunction(p)&&p.call(this.element[0],m,n)===false||m.isDefaultPrevented())}};c.widget.defaults={disabled:false};c.ui.mouse={_mouseInit:function(){var j=this;this.element.bind("mousedown."+this.widgetName,function(k){return j._mouseDown(k)}).bind("click."+this.widgetName,function(k){if(j._preventClickEvent){j._preventClickEvent=false;k.stopImmediatePropagation();return false}});if(c.browser.msie){this._mouseUnselectable=this.element.attr("unselectable");this.element.attr("unselectable","on")}this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);(c.browser.msie&&this.element.attr("unselectable",this._mouseUnselectable))},_mouseDown:function(l){l.originalEvent=l.originalEvent||{};if(l.originalEvent.mouseHandled){return}(this._mouseStarted&&this._mouseUp(l));this._mouseDownEvent=l;var k=this,m=(l.which==1),j=(typeof this.options.cancel=="string"?c(l.target).parents().add(l.target).filter(this.options.cancel).length:false);if(!m||j||!this._mouseCapture(l)){return true}this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){k.mouseDelayMet=true},this.options.delay)}if(this._mouseDistanceMet(l)&&this._mouseDelayMet(l)){this._mouseStarted=(this._mouseStart(l)!==false);if(!this._mouseStarted){l.preventDefault();return true}}this._mouseMoveDelegate=function(n){return k._mouseMove(n)};this._mouseUpDelegate=function(n){return k._mouseUp(n)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);(c.browser.safari||l.preventDefault());l.originalEvent.mouseHandled=true;return true},_mouseMove:function(j){if(c.browser.msie&&!j.button){return this._mouseUp(j)}if(this._mouseStarted){this._mouseDrag(j);return j.preventDefault()}if(this._mouseDistanceMet(j)&&this._mouseDelayMet(j)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,j)!==false);(this._mouseStarted?this._mouseDrag(j):this._mouseUp(j))}return !this._mouseStarted},_mouseUp:function(j){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=(j.target==this._mouseDownEvent.target);this._mouseStop(j)}return false},_mouseDistanceMet:function(j){return(Math.max(Math.abs(this._mouseDownEvent.pageX-j.pageX),Math.abs(this._mouseDownEvent.pageY-j.pageY))>=this.options.distance)},_mouseDelayMet:function(j){return this.mouseDelayMet},_mouseStart:function(j){},_mouseDrag:function(j){},_mouseStop:function(j){},_mouseCapture:function(j){return true}};c.ui.mouse.defaults={cancel:null,distance:1,delay:0}})(jQuery);;/*
 * jQuery UI Draggable 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Draggables
 *
 * Depends:
 *	ui.core.js
 */
(function(a){a.widget("ui.draggable",a.extend({},a.ui.mouse,{_init:function(){if(this.options.helper=="original"&&!(/^(?:r|a|f)/).test(this.element.css("position"))){this.element[0].style.position="relative"}(this.options.addClasses&&this.element.addClass("ui-draggable"));(this.options.disabled&&this.element.addClass("ui-draggable-disabled"));this._mouseInit()},destroy:function(){if(!this.element.data("draggable")){return}this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy()},_mouseCapture:function(b){var c=this.options;if(this.helper||c.disabled||a(b.target).is(".ui-resizable-handle")){return false}this.handle=this._getHandle(b);if(!this.handle){return false}return true},_mouseStart:function(b){var c=this.options;this.helper=this._createHelper(b);this._cacheHelperProportions();if(a.ui.ddmanager){a.ui.ddmanager.current=this}this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(b);this.originalPageX=b.pageX;this.originalPageY=b.pageY;if(c.cursorAt){this._adjustOffsetFromHelper(c.cursorAt)}if(c.containment){this._setContainment()}this._trigger("start",b);this._cacheHelperProportions();if(a.ui.ddmanager&&!c.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,b)}this.helper.addClass("ui-draggable-dragging");this._mouseDrag(b,true);return true},_mouseDrag:function(b,d){this.position=this._generatePosition(b);this.positionAbs=this._convertPositionTo("absolute");if(!d){var c=this._uiHash();this._trigger("drag",b,c);this.position=c.position}if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}if(a.ui.ddmanager){a.ui.ddmanager.drag(this,b)}return false},_mouseStop:function(c){var d=false;if(a.ui.ddmanager&&!this.options.dropBehaviour){d=a.ui.ddmanager.drop(this,c)}if(this.dropped){d=this.dropped;this.dropped=false}if((this.options.revert=="invalid"&&!d)||(this.options.revert=="valid"&&d)||this.options.revert===true||(a.isFunction(this.options.revert)&&this.options.revert.call(this.element,d))){var b=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){b._trigger("stop",c);b._clear()})}else{this._trigger("stop",c);this._clear()}return false},_getHandle:function(b){var c=!this.options.handle||!a(this.options.handle,this.element).length?true:false;a(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==b.target){c=true}});return c},_createHelper:function(c){var d=this.options;var b=a.isFunction(d.helper)?a(d.helper.apply(this.element[0],[c])):(d.helper=="clone"?this.element.clone():this.element);if(!b.parents("body").length){b.appendTo((d.appendTo=="parent"?this.element[0].parentNode:d.appendTo))}if(b[0]!=this.element[0]&&!(/(fixed|absolute)/).test(b.css("position"))){b.css("position","absolute")}return b},_adjustOffsetFromHelper:function(b){if(b.left!=undefined){this.offset.click.left=b.left+this.margins.left}if(b.right!=undefined){this.offset.click.left=this.helperProportions.width-b.right+this.margins.left}if(b.top!=undefined){this.offset.click.top=b.top+this.margins.top}if(b.bottom!=undefined){this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){b.left+=this.scrollParent.scrollLeft();b.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){b={top:0,left:0}}return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var b=this.element.position();return{top:b.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:b.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.element.css("marginLeft"),10)||0),top:(parseInt(this.element.css("marginTop"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e=this.options;if(e.containment=="parent"){e.containment=this.helper[0].parentNode}if(e.containment=="document"||e.containment=="window"){this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(e.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(e.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(e.containment)&&e.containment.constructor!=Array){var c=a(e.containment)[0];if(!c){return}var d=a(e.containment).offset();var b=(a(c).css("overflow")!="hidden");this.containment=[d.left+(parseInt(a(c).css("borderLeftWidth"),10)||0)+(parseInt(a(c).css("paddingLeft"),10)||0)-this.margins.left,d.top+(parseInt(a(c).css("borderTopWidth"),10)||0)+(parseInt(a(c).css("paddingTop"),10)||0)-this.margins.top,d.left+(b?Math.max(c.scrollWidth,c.offsetWidth):c.offsetWidth)-(parseInt(a(c).css("borderLeftWidth"),10)||0)-(parseInt(a(c).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,d.top+(b?Math.max(c.scrollHeight,c.offsetHeight):c.offsetHeight)-(parseInt(a(c).css("borderTopWidth"),10)||0)-(parseInt(a(c).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}else{if(e.containment.constructor==Array){this.containment=e.containment}}},_convertPositionTo:function(f,h){if(!h){h=this.position}var c=f=="absolute"?1:-1;var e=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=(/(html|body)/i).test(b[0].tagName);return{top:(h.top+this.offset.relative.top*c+this.offset.parent.top*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(g?0:b.scrollTop()))*c)),left:(h.left+this.offset.relative.left*c+this.offset.parent.left*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:b.scrollLeft())*c))}},_generatePosition:function(e){var h=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,i=(/(html|body)/i).test(b[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0])){this.offset.relative=this._getRelativeOffset()}var d=e.pageX;var c=e.pageY;if(this.originalPosition){if(this.containment){if(e.pageX-this.offset.click.left<this.containment[0]){d=this.containment[0]+this.offset.click.left}if(e.pageY-this.offset.click.top<this.containment[1]){c=this.containment[1]+this.offset.click.top}if(e.pageX-this.offset.click.left>this.containment[2]){d=this.containment[2]+this.offset.click.left}if(e.pageY-this.offset.click.top>this.containment[3]){c=this.containment[3]+this.offset.click.top}}if(h.grid){var g=this.originalPageY+Math.round((c-this.originalPageY)/h.grid[1])*h.grid[1];c=this.containment?(!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:(!(g-this.offset.click.top<this.containment[1])?g-h.grid[1]:g+h.grid[1])):g;var f=this.originalPageX+Math.round((d-this.originalPageX)/h.grid[0])*h.grid[0];d=this.containment?(!(f-this.offset.click.left<this.containment[0]||f-this.offset.click.left>this.containment[2])?f:(!(f-this.offset.click.left<this.containment[0])?f-h.grid[0]:f+h.grid[0])):f}}return{top:(c-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(i?0:b.scrollTop())))),left:(d-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:b.scrollLeft())))}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");if(this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval){this.helper.remove()}this.helper=null;this.cancelHelperRemoval=false},_trigger:function(b,c,d){d=d||this._uiHash();a.ui.plugin.call(this,b,[c,d]);if(b=="drag"){this.positionAbs=this._convertPositionTo("absolute")}return a.widget.prototype._trigger.call(this,b,c,d)},plugins:{},_uiHash:function(b){return{helper:this.helper,position:this.position,absolutePosition:this.positionAbs,offset:this.positionAbs}}}));a.extend(a.ui.draggable,{version:"1.7.2",eventPrefix:"drag",defaults:{addClasses:true,appendTo:"parent",axis:false,cancel:":input,option",connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,delay:0,distance:1,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false}});a.ui.plugin.add("draggable","connectToSortable",{start:function(c,e){var d=a(this).data("draggable"),f=d.options,b=a.extend({},e,{item:d.element});d.sortables=[];a(f.connectToSortable).each(function(){var g=a.data(this,"sortable");if(g&&!g.options.disabled){d.sortables.push({instance:g,shouldRevert:g.options.revert});g._refreshItems();g._trigger("activate",c,b)}})},stop:function(c,e){var d=a(this).data("draggable"),b=a.extend({},e,{item:d.element});a.each(d.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;d.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert){this.instance.options.revert=true}this.instance._mouseStop(c);this.instance.options.helper=this.instance.options._helper;if(d.options.helper=="original"){this.instance.currentItem.css({top:"auto",left:"auto"})}}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",c,b)}})},drag:function(c,f){var e=a(this).data("draggable"),b=this;var d=function(i){var n=this.offset.click.top,m=this.offset.click.left;var g=this.positionAbs.top,k=this.positionAbs.left;var j=i.height,l=i.width;var p=i.top,h=i.left;return a.ui.isOver(g+n,k+m,p,h,j,l)};a.each(e.sortables,function(g){this.instance.positionAbs=e.positionAbs;this.instance.helperProportions=e.helperProportions;this.instance.offset.click=e.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver=1;this.instance.currentItem=a(b).clone().appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return f.helper[0]};c.target=this.instance.currentItem[0];this.instance._mouseCapture(c,true);this.instance._mouseStart(c,true,true);this.instance.offset.click.top=e.offset.click.top;this.instance.offset.click.left=e.offset.click.left;this.instance.offset.parent.left-=e.offset.parent.left-this.instance.offset.parent.left;this.instance.offset.parent.top-=e.offset.parent.top-this.instance.offset.parent.top;e._trigger("toSortable",c);e.dropped=this.instance.element;e.currentItem=e.element;this.instance.fromOutside=e}if(this.instance.currentItem){this.instance._mouseDrag(c)}}else{if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",c,this.instance._uiHash(this.instance));this.instance._mouseStop(c,true);this.instance.options.helper=this.instance.options._helper;this.instance.currentItem.remove();if(this.instance.placeholder){this.instance.placeholder.remove()}e._trigger("fromSortable",c);e.dropped=false}}})}});a.ui.plugin.add("draggable","cursor",{start:function(c,d){var b=a("body"),e=a(this).data("draggable").options;if(b.css("cursor")){e._cursor=b.css("cursor")}b.css("cursor",e.cursor)},stop:function(b,c){var d=a(this).data("draggable").options;if(d._cursor){a("body").css("cursor",d._cursor)}}});a.ui.plugin.add("draggable","iframeFix",{start:function(b,c){var d=a(this).data("draggable").options;a(d.iframeFix===true?"iframe":d.iframeFix).each(function(){a('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1000}).css(a(this).offset()).appendTo("body")})},stop:function(b,c){a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)})}});a.ui.plugin.add("draggable","opacity",{start:function(c,d){var b=a(d.helper),e=a(this).data("draggable").options;if(b.css("opacity")){e._opacity=b.css("opacity")}b.css("opacity",e.opacity)},stop:function(b,c){var d=a(this).data("draggable").options;if(d._opacity){a(c.helper).css("opacity",d._opacity)}}});a.ui.plugin.add("draggable","scroll",{start:function(c,d){var b=a(this).data("draggable");if(b.scrollParent[0]!=document&&b.scrollParent[0].tagName!="HTML"){b.overflowOffset=b.scrollParent.offset()}},drag:function(d,e){var c=a(this).data("draggable"),f=c.options,b=false;if(c.scrollParent[0]!=document&&c.scrollParent[0].tagName!="HTML"){if(!f.axis||f.axis!="x"){if((c.overflowOffset.top+c.scrollParent[0].offsetHeight)-d.pageY<f.scrollSensitivity){c.scrollParent[0].scrollTop=b=c.scrollParent[0].scrollTop+f.scrollSpeed}else{if(d.pageY-c.overflowOffset.top<f.scrollSensitivity){c.scrollParent[0].scrollTop=b=c.scrollParent[0].scrollTop-f.scrollSpeed}}}if(!f.axis||f.axis!="y"){if((c.overflowOffset.left+c.scrollParent[0].offsetWidth)-d.pageX<f.scrollSensitivity){c.scrollParent[0].scrollLeft=b=c.scrollParent[0].scrollLeft+f.scrollSpeed}else{if(d.pageX-c.overflowOffset.left<f.scrollSensitivity){c.scrollParent[0].scrollLeft=b=c.scrollParent[0].scrollLeft-f.scrollSpeed}}}}else{if(!f.axis||f.axis!="x"){if(d.pageY-a(document).scrollTop()<f.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()-f.scrollSpeed)}else{if(a(window).height()-(d.pageY-a(document).scrollTop())<f.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()+f.scrollSpeed)}}}if(!f.axis||f.axis!="y"){if(d.pageX-a(document).scrollLeft()<f.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()-f.scrollSpeed)}else{if(a(window).width()-(d.pageX-a(document).scrollLeft())<f.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()+f.scrollSpeed)}}}}if(b!==false&&a.ui.ddmanager&&!f.dropBehaviour){a.ui.ddmanager.prepareOffsets(c,d)}}});a.ui.plugin.add("draggable","snap",{start:function(c,d){var b=a(this).data("draggable"),e=b.options;b.snapElements=[];a(e.snap.constructor!=String?(e.snap.items||":data(draggable)"):e.snap).each(function(){var g=a(this);var f=g.offset();if(this!=b.element[0]){b.snapElements.push({item:this,width:g.outerWidth(),height:g.outerHeight(),top:f.top,left:f.left})}})},drag:function(u,p){var g=a(this).data("draggable"),q=g.options;var y=q.snapTolerance;var x=p.offset.left,w=x+g.helperProportions.width,f=p.offset.top,e=f+g.helperProportions.height;for(var v=g.snapElements.length-1;v>=0;v--){var s=g.snapElements[v].left,n=s+g.snapElements[v].width,m=g.snapElements[v].top,A=m+g.snapElements[v].height;if(!((s-y<x&&x<n+y&&m-y<f&&f<A+y)||(s-y<x&&x<n+y&&m-y<e&&e<A+y)||(s-y<w&&w<n+y&&m-y<f&&f<A+y)||(s-y<w&&w<n+y&&m-y<e&&e<A+y))){if(g.snapElements[v].snapping){(g.options.snap.release&&g.options.snap.release.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=false;continue}if(q.snapMode!="inner"){var c=Math.abs(m-e)<=y;var z=Math.abs(A-f)<=y;var j=Math.abs(s-w)<=y;var k=Math.abs(n-x)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m-g.helperProportions.height,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s-g.helperProportions.width}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n}).left-g.margins.left}}var h=(c||z||j||k);if(q.snapMode!="outer"){var c=Math.abs(m-f)<=y;var z=Math.abs(A-e)<=y;var j=Math.abs(s-x)<=y;var k=Math.abs(n-w)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A-g.helperProportions.height,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n-g.helperProportions.width}).left-g.margins.left}}if(!g.snapElements[v].snapping&&(c||z||j||k||h)){(g.options.snap.snap&&g.options.snap.snap.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=(c||z||j||k||h)}}});a.ui.plugin.add("draggable","stack",{start:function(b,c){var e=a(this).data("draggable").options;var d=a.makeArray(a(e.stack.group)).sort(function(g,f){return(parseInt(a(g).css("zIndex"),10)||e.stack.min)-(parseInt(a(f).css("zIndex"),10)||e.stack.min)});a(d).each(function(f){this.style.zIndex=e.stack.min+f});this[0].style.zIndex=e.stack.min+d.length}});a.ui.plugin.add("draggable","zIndex",{start:function(c,d){var b=a(d.helper),e=a(this).data("draggable").options;if(b.css("zIndex")){e._zIndex=b.css("zIndex")}b.css("zIndex",e.zIndex)},stop:function(b,c){var d=a(this).data("draggable").options;if(d._zIndex){a(c.helper).css("zIndex",d._zIndex)}}})})(jQuery);;/*
 * jQuery UI Droppable 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Droppables
 *
 * Depends:
 *	ui.core.js
 *	ui.draggable.js
 */
(function(a){a.widget("ui.droppable",{_init:function(){var c=this.options,b=c.accept;this.isover=0;this.isout=1;this.options.accept=this.options.accept&&a.isFunction(this.options.accept)?this.options.accept:function(e){return e.is(b)};this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};a.ui.ddmanager.droppables[this.options.scope]=a.ui.ddmanager.droppables[this.options.scope]||[];a.ui.ddmanager.droppables[this.options.scope].push(this);(this.options.addClasses&&this.element.addClass("ui-droppable"))},destroy:function(){var b=a.ui.ddmanager.droppables[this.options.scope];for(var c=0;c<b.length;c++){if(b[c]==this){b.splice(c,1)}}this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable")},_setData:function(b,c){if(b=="accept"){this.options.accept=c&&a.isFunction(c)?c:function(e){return e.is(c)}}else{a.widget.prototype._setData.apply(this,arguments)}},_activate:function(c){var b=a.ui.ddmanager.current;if(this.options.activeClass){this.element.addClass(this.options.activeClass)}(b&&this._trigger("activate",c,this.ui(b)))},_deactivate:function(c){var b=a.ui.ddmanager.current;if(this.options.activeClass){this.element.removeClass(this.options.activeClass)}(b&&this._trigger("deactivate",c,this.ui(b)))},_over:function(c){var b=a.ui.ddmanager.current;if(!b||(b.currentItem||b.element)[0]==this.element[0]){return}if(this.options.accept.call(this.element[0],(b.currentItem||b.element))){if(this.options.hoverClass){this.element.addClass(this.options.hoverClass)}this._trigger("over",c,this.ui(b))}},_out:function(c){var b=a.ui.ddmanager.current;if(!b||(b.currentItem||b.element)[0]==this.element[0]){return}if(this.options.accept.call(this.element[0],(b.currentItem||b.element))){if(this.options.hoverClass){this.element.removeClass(this.options.hoverClass)}this._trigger("out",c,this.ui(b))}},_drop:function(c,d){var b=d||a.ui.ddmanager.current;if(!b||(b.currentItem||b.element)[0]==this.element[0]){return false}var e=false;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var f=a.data(this,"droppable");if(f.options.greedy&&a.ui.intersect(b,a.extend(f,{offset:f.element.offset()}),f.options.tolerance)){e=true;return false}});if(e){return false}if(this.options.accept.call(this.element[0],(b.currentItem||b.element))){if(this.options.activeClass){this.element.removeClass(this.options.activeClass)}if(this.options.hoverClass){this.element.removeClass(this.options.hoverClass)}this._trigger("drop",c,this.ui(b));return this.element}return false},ui:function(b){return{draggable:(b.currentItem||b.element),helper:b.helper,position:b.position,absolutePosition:b.positionAbs,offset:b.positionAbs}}});a.extend(a.ui.droppable,{version:"1.7.2",eventPrefix:"drop",defaults:{accept:"*",activeClass:false,addClasses:true,greedy:false,hoverClass:false,scope:"default",tolerance:"intersect"}});a.ui.intersect=function(q,j,o){if(!j.offset){return false}var e=(q.positionAbs||q.position.absolute).left,d=e+q.helperProportions.width,n=(q.positionAbs||q.position.absolute).top,m=n+q.helperProportions.height;var g=j.offset.left,c=g+j.proportions.width,p=j.offset.top,k=p+j.proportions.height;switch(o){case"fit":return(g<e&&d<c&&p<n&&m<k);break;case"intersect":return(g<e+(q.helperProportions.width/2)&&d-(q.helperProportions.width/2)<c&&p<n+(q.helperProportions.height/2)&&m-(q.helperProportions.height/2)<k);break;case"pointer":var h=((q.positionAbs||q.position.absolute).left+(q.clickOffset||q.offset.click).left),i=((q.positionAbs||q.position.absolute).top+(q.clickOffset||q.offset.click).top),f=a.ui.isOver(i,h,p,g,j.proportions.height,j.proportions.width);return f;break;case"touch":return((n>=p&&n<=k)||(m>=p&&m<=k)||(n<p&&m>k))&&((e>=g&&e<=c)||(d>=g&&d<=c)||(e<g&&d>c));break;default:return false;break}};a.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(e,g){var b=a.ui.ddmanager.droppables[e.options.scope];var f=g?g.type:null;var h=(e.currentItem||e.element).find(":data(droppable)").andSelf();droppablesLoop:for(var d=0;d<b.length;d++){if(b[d].options.disabled||(e&&!b[d].options.accept.call(b[d].element[0],(e.currentItem||e.element)))){continue}for(var c=0;c<h.length;c++){if(h[c]==b[d].element[0]){b[d].proportions.height=0;continue droppablesLoop}}b[d].visible=b[d].element.css("display")!="none";if(!b[d].visible){continue}b[d].offset=b[d].element.offset();b[d].proportions={width:b[d].element[0].offsetWidth,height:b[d].element[0].offsetHeight};if(f=="mousedown"){b[d]._activate.call(b[d],g)}}},drop:function(b,c){var d=false;a.each(a.ui.ddmanager.droppables[b.options.scope],function(){if(!this.options){return}if(!this.options.disabled&&this.visible&&a.ui.intersect(b,this,this.options.tolerance)){d=this._drop.call(this,c)}if(!this.options.disabled&&this.visible&&this.options.accept.call(this.element[0],(b.currentItem||b.element))){this.isout=1;this.isover=0;this._deactivate.call(this,c)}});return d},drag:function(b,c){if(b.options.refreshPositions){a.ui.ddmanager.prepareOffsets(b,c)}a.each(a.ui.ddmanager.droppables[b.options.scope],function(){if(this.options.disabled||this.greedyChild||!this.visible){return}var e=a.ui.intersect(b,this,this.options.tolerance);var g=!e&&this.isover==1?"isout":(e&&this.isover==0?"isover":null);if(!g){return}var f;if(this.options.greedy){var d=this.element.parents(":data(droppable):eq(0)");if(d.length){f=a.data(d[0],"droppable");f.greedyChild=(g=="isover"?1:0)}}if(f&&g=="isover"){f.isover=0;f.isout=1;f._out.call(f,c)}this[g]=1;this[g=="isout"?"isover":"isout"]=0;this[g=="isover"?"_over":"_out"].call(this,c);if(f&&g=="isout"){f.isout=0;f.isover=1;f._over.call(f,c)}})}}})(jQuery);;/*
 * jQuery UI Resizable 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Resizables
 *
 * Depends:
 *	ui.core.js
 */
(function(c){c.widget("ui.resizable",c.extend({},c.ui.mouse,{_init:function(){var e=this,j=this.options;this.element.addClass("ui-resizable");c.extend(this,{_aspectRatio:!!(j.aspectRatio),aspectRatio:j.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:j.helper||j.ghost||j.animate?j.helper||"ui-resizable-helper":null});if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)){if(/relative/.test(this.element.css("position"))&&c.browser.opera){this.element.css({position:"relative",top:"auto",left:"auto"})}this.element.wrap(c('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")}));this.element=this.element.parent().data("resizable",this.element.data("resizable"));this.elementIsWrapper=true;this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")});this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0});this.originalResizeStyle=this.originalElement.css("resize");this.originalElement.css("resize","none");this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"}));this.originalElement.css({margin:this.originalElement.css("margin")});this._proportionallyResize()}this.handles=j.handles||(!c(".ui-resizable-handle",this.element).length?"e,s,se":{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"});if(this.handles.constructor==String){if(this.handles=="all"){this.handles="n,e,s,w,se,sw,ne,nw"}var k=this.handles.split(",");this.handles={};for(var f=0;f<k.length;f++){var h=c.trim(k[f]),d="ui-resizable-"+h;var g=c('<div class="ui-resizable-handle '+d+'"></div>');if(/sw|se|ne|nw/.test(h)){g.css({zIndex:++j.zIndex})}if("se"==h){g.addClass("ui-icon ui-icon-gripsmall-diagonal-se")}this.handles[h]=".ui-resizable-"+h;this.element.append(g)}}this._renderAxis=function(p){p=p||this.element;for(var m in this.handles){if(this.handles[m].constructor==String){this.handles[m]=c(this.handles[m],this.element).show()}if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var n=c(this.handles[m],this.element),o=0;o=/sw|ne|nw|se|n|s/.test(m)?n.outerHeight():n.outerWidth();var l=["padding",/ne|nw|n/.test(m)?"Top":/se|sw|s/.test(m)?"Bottom":/^e$/.test(m)?"Right":"Left"].join("");p.css(l,o);this._proportionallyResize()}if(!c(this.handles[m]).length){continue}}};this._renderAxis(this.element);this._handles=c(".ui-resizable-handle",this.element).disableSelection();this._handles.mouseover(function(){if(!e.resizing){if(this.className){var i=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)}e.axis=i&&i[1]?i[1]:"se"}});if(j.autoHide){this._handles.hide();c(this.element).addClass("ui-resizable-autohide").hover(function(){c(this).removeClass("ui-resizable-autohide");e._handles.show()},function(){if(!e.resizing){c(this).addClass("ui-resizable-autohide");e._handles.hide()}})}this._mouseInit()},destroy:function(){this._mouseDestroy();var d=function(f){c(f).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){d(this.element);var e=this.element;e.parent().append(this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")})).end().remove()}this.originalElement.css("resize",this.originalResizeStyle);d(this.originalElement)},_mouseCapture:function(e){var f=false;for(var d in this.handles){if(c(this.handles[d])[0]==e.target){f=true}}return this.options.disabled||!!f},_mouseStart:function(f){var i=this.options,e=this.element.position(),d=this.element;this.resizing=true;this.documentScroll={top:c(document).scrollTop(),left:c(document).scrollLeft()};if(d.is(".ui-draggable")||(/absolute/).test(d.css("position"))){d.css({position:"absolute",top:e.top,left:e.left})}if(c.browser.opera&&(/relative/).test(d.css("position"))){d.css({position:"relative",top:"auto",left:"auto"})}this._renderProxy();var j=b(this.helper.css("left")),g=b(this.helper.css("top"));if(i.containment){j+=c(i.containment).scrollLeft()||0;g+=c(i.containment).scrollTop()||0}this.offset=this.helper.offset();this.position={left:j,top:g};this.size=this._helper?{width:d.outerWidth(),height:d.outerHeight()}:{width:d.width(),height:d.height()};this.originalSize=this._helper?{width:d.outerWidth(),height:d.outerHeight()}:{width:d.width(),height:d.height()};this.originalPosition={left:j,top:g};this.sizeDiff={width:d.outerWidth()-d.width(),height:d.outerHeight()-d.height()};this.originalMousePosition={left:f.pageX,top:f.pageY};this.aspectRatio=(typeof i.aspectRatio=="number")?i.aspectRatio:((this.originalSize.width/this.originalSize.height)||1);var h=c(".ui-resizable-"+this.axis).css("cursor");c("body").css("cursor",h=="auto"?this.axis+"-resize":h);d.addClass("ui-resizable-resizing");this._propagate("start",f);return true},_mouseDrag:function(d){var g=this.helper,f=this.options,l={},p=this,i=this.originalMousePosition,m=this.axis;var q=(d.pageX-i.left)||0,n=(d.pageY-i.top)||0;var h=this._change[m];if(!h){return false}var k=h.apply(this,[d,q,n]),j=c.browser.msie&&c.browser.version<7,e=this.sizeDiff;if(this._aspectRatio||d.shiftKey){k=this._updateRatio(k,d)}k=this._respectSize(k,d);this._propagate("resize",d);g.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"});if(!this._helper&&this._proportionallyResizeElements.length){this._proportionallyResize()}this._updateCache(k);this._trigger("resize",d,this.ui());return false},_mouseStop:function(g){this.resizing=false;var h=this.options,l=this;if(this._helper){var f=this._proportionallyResizeElements,d=f.length&&(/textarea/i).test(f[0].nodeName),e=d&&c.ui.hasScroll(f[0],"left")?0:l.sizeDiff.height,j=d?0:l.sizeDiff.width;var m={width:(l.size.width-j),height:(l.size.height-e)},i=(parseInt(l.element.css("left"),10)+(l.position.left-l.originalPosition.left))||null,k=(parseInt(l.element.css("top"),10)+(l.position.top-l.originalPosition.top))||null;if(!h.animate){this.element.css(c.extend(m,{top:k,left:i}))}l.helper.height(l.size.height);l.helper.width(l.size.width);if(this._helper&&!h.animate){this._proportionallyResize()}}c("body").css("cursor","auto");this.element.removeClass("ui-resizable-resizing");this._propagate("stop",g);if(this._helper){this.helper.remove()}return false},_updateCache:function(d){var e=this.options;this.offset=this.helper.offset();if(a(d.left)){this.position.left=d.left}if(a(d.top)){this.position.top=d.top}if(a(d.height)){this.size.height=d.height}if(a(d.width)){this.size.width=d.width}},_updateRatio:function(g,f){var h=this.options,i=this.position,e=this.size,d=this.axis;if(g.height){g.width=(e.height*this.aspectRatio)}else{if(g.width){g.height=(e.width/this.aspectRatio)}}if(d=="sw"){g.left=i.left+(e.width-g.width);g.top=null}if(d=="nw"){g.top=i.top+(e.height-g.height);g.left=i.left+(e.width-g.width)}return g},_respectSize:function(k,f){var i=this.helper,h=this.options,q=this._aspectRatio||f.shiftKey,p=this.axis,s=a(k.width)&&h.maxWidth&&(h.maxWidth<k.width),l=a(k.height)&&h.maxHeight&&(h.maxHeight<k.height),g=a(k.width)&&h.minWidth&&(h.minWidth>k.width),r=a(k.height)&&h.minHeight&&(h.minHeight>k.height);if(g){k.width=h.minWidth}if(r){k.height=h.minHeight}if(s){k.width=h.maxWidth}if(l){k.height=h.maxHeight}var e=this.originalPosition.left+this.originalSize.width,n=this.position.top+this.size.height;var j=/sw|nw|w/.test(p),d=/nw|ne|n/.test(p);if(g&&j){k.left=e-h.minWidth}if(s&&j){k.left=e-h.maxWidth}if(r&&d){k.top=n-h.minHeight}if(l&&d){k.top=n-h.maxHeight}var m=!k.width&&!k.height;if(m&&!k.left&&k.top){k.top=null}else{if(m&&!k.top&&k.left){k.left=null}}return k},_proportionallyResize:function(){var j=this.options;if(!this._proportionallyResizeElements.length){return}var f=this.helper||this.element;for(var e=0;e<this._proportionallyResizeElements.length;e++){var g=this._proportionallyResizeElements[e];if(!this.borderDif){var d=[g.css("borderTopWidth"),g.css("borderRightWidth"),g.css("borderBottomWidth"),g.css("borderLeftWidth")],h=[g.css("paddingTop"),g.css("paddingRight"),g.css("paddingBottom"),g.css("paddingLeft")];this.borderDif=c.map(d,function(k,m){var l=parseInt(k,10)||0,n=parseInt(h[m],10)||0;return l+n})}if(c.browser.msie&&!(!(c(f).is(":hidden")||c(f).parents(":hidden").length))){continue}g.css({height:(f.height()-this.borderDif[0]-this.borderDif[2])||0,width:(f.width()-this.borderDif[1]-this.borderDif[3])||0})}},_renderProxy:function(){var e=this.element,h=this.options;this.elementOffset=e.offset();if(this._helper){this.helper=this.helper||c('<div style="overflow:hidden;"></div>');var d=c.browser.msie&&c.browser.version<7,f=(d?1:0),g=(d?2:-1);this.helper.addClass(this._helper).css({width:this.element.outerWidth()+g,height:this.element.outerHeight()+g,position:"absolute",left:this.elementOffset.left-f+"px",top:this.elementOffset.top-f+"px",zIndex:++h.zIndex});this.helper.appendTo("body").disableSelection()}else{this.helper=this.element}},_change:{e:function(f,e,d){return{width:this.originalSize.width+e}},w:function(g,e,d){var i=this.options,f=this.originalSize,h=this.originalPosition;return{left:h.left+e,width:f.width-e}},n:function(g,e,d){var i=this.options,f=this.originalSize,h=this.originalPosition;return{top:h.top+d,height:f.height-d}},s:function(f,e,d){return{height:this.originalSize.height+d}},se:function(f,e,d){return c.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[f,e,d]))},sw:function(f,e,d){return c.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[f,e,d]))},ne:function(f,e,d){return c.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[f,e,d]))},nw:function(f,e,d){return c.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[f,e,d]))}},_propagate:function(e,d){c.ui.plugin.call(this,e,[d,this.ui()]);(e!="resize"&&this._trigger(e,d,this.ui()))},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}));c.extend(c.ui.resizable,{version:"1.7.2",eventPrefix:"resize",defaults:{alsoResize:false,animate:false,animateDuration:"slow",animateEasing:"swing",aspectRatio:false,autoHide:false,cancel:":input,option",containment:false,delay:0,distance:1,ghost:false,grid:false,handles:"e,s,se",helper:false,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1000}});c.ui.plugin.add("resizable","alsoResize",{start:function(e,f){var d=c(this).data("resizable"),g=d.options;_store=function(h){c(h).each(function(){c(this).data("resizable-alsoresize",{width:parseInt(c(this).width(),10),height:parseInt(c(this).height(),10),left:parseInt(c(this).css("left"),10),top:parseInt(c(this).css("top"),10)})})};if(typeof(g.alsoResize)=="object"&&!g.alsoResize.parentNode){if(g.alsoResize.length){g.alsoResize=g.alsoResize[0];_store(g.alsoResize)}else{c.each(g.alsoResize,function(h,i){_store(h)})}}else{_store(g.alsoResize)}},resize:function(f,h){var e=c(this).data("resizable"),i=e.options,g=e.originalSize,k=e.originalPosition;var j={height:(e.size.height-g.height)||0,width:(e.size.width-g.width)||0,top:(e.position.top-k.top)||0,left:(e.position.left-k.left)||0},d=function(l,m){c(l).each(function(){var p=c(this),q=c(this).data("resizable-alsoresize"),o={},n=m&&m.length?m:["width","height","top","left"];c.each(n||["width","height","top","left"],function(r,t){var s=(q[t]||0)+(j[t]||0);if(s&&s>=0){o[t]=s||null}});if(/relative/.test(p.css("position"))&&c.browser.opera){e._revertToRelativePosition=true;p.css({position:"absolute",top:"auto",left:"auto"})}p.css(o)})};if(typeof(i.alsoResize)=="object"&&!i.alsoResize.nodeType){c.each(i.alsoResize,function(l,m){d(l,m)})}else{d(i.alsoResize)}},stop:function(e,f){var d=c(this).data("resizable");if(d._revertToRelativePosition&&c.browser.opera){d._revertToRelativePosition=false;el.css({position:"relative"})}c(this).removeData("resizable-alsoresize-start")}});c.ui.plugin.add("resizable","animate",{stop:function(h,m){var n=c(this).data("resizable"),i=n.options;var g=n._proportionallyResizeElements,d=g.length&&(/textarea/i).test(g[0].nodeName),e=d&&c.ui.hasScroll(g[0],"left")?0:n.sizeDiff.height,k=d?0:n.sizeDiff.width;var f={width:(n.size.width-k),height:(n.size.height-e)},j=(parseInt(n.element.css("left"),10)+(n.position.left-n.originalPosition.left))||null,l=(parseInt(n.element.css("top"),10)+(n.position.top-n.originalPosition.top))||null;n.element.animate(c.extend(f,l&&j?{top:l,left:j}:{}),{duration:i.animateDuration,easing:i.animateEasing,step:function(){var o={width:parseInt(n.element.css("width"),10),height:parseInt(n.element.css("height"),10),top:parseInt(n.element.css("top"),10),left:parseInt(n.element.css("left"),10)};if(g&&g.length){c(g[0]).css({width:o.width,height:o.height})}n._updateCache(o);n._propagate("resize",h)}})}});c.ui.plugin.add("resizable","containment",{start:function(e,q){var s=c(this).data("resizable"),i=s.options,k=s.element;var f=i.containment,j=(f instanceof c)?f.get(0):(/parent/.test(f))?k.parent().get(0):f;if(!j){return}s.containerElement=c(j);if(/document/.test(f)||f==document){s.containerOffset={left:0,top:0};s.containerPosition={left:0,top:0};s.parentData={element:c(document),left:0,top:0,width:c(document).width(),height:c(document).height()||document.body.parentNode.scrollHeight}}else{var m=c(j),h=[];c(["Top","Right","Left","Bottom"]).each(function(p,o){h[p]=b(m.css("padding"+o))});s.containerOffset=m.offset();s.containerPosition=m.position();s.containerSize={height:(m.innerHeight()-h[3]),width:(m.innerWidth()-h[1])};var n=s.containerOffset,d=s.containerSize.height,l=s.containerSize.width,g=(c.ui.hasScroll(j,"left")?j.scrollWidth:l),r=(c.ui.hasScroll(j)?j.scrollHeight:d);s.parentData={element:j,left:n.left,top:n.top,width:g,height:r}}},resize:function(f,p){var s=c(this).data("resizable"),h=s.options,e=s.containerSize,n=s.containerOffset,l=s.size,m=s.position,q=s._aspectRatio||f.shiftKey,d={top:0,left:0},g=s.containerElement;if(g[0]!=document&&(/static/).test(g.css("position"))){d=n}if(m.left<(s._helper?n.left:0)){s.size.width=s.size.width+(s._helper?(s.position.left-n.left):(s.position.left-d.left));if(q){s.size.height=s.size.width/h.aspectRatio}s.position.left=h.helper?n.left:0}if(m.top<(s._helper?n.top:0)){s.size.height=s.size.height+(s._helper?(s.position.top-n.top):s.position.top);if(q){s.size.width=s.size.height*h.aspectRatio}s.position.top=s._helper?n.top:0}s.offset.left=s.parentData.left+s.position.left;s.offset.top=s.parentData.top+s.position.top;var k=Math.abs((s._helper?s.offset.left-d.left:(s.offset.left-d.left))+s.sizeDiff.width),r=Math.abs((s._helper?s.offset.top-d.top:(s.offset.top-n.top))+s.sizeDiff.height);var j=s.containerElement.get(0)==s.element.parent().get(0),i=/relative|absolute/.test(s.containerElement.css("position"));if(j&&i){k-=s.parentData.left}if(k+s.size.width>=s.parentData.width){s.size.width=s.parentData.width-k;if(q){s.size.height=s.size.width/s.aspectRatio}}if(r+s.size.height>=s.parentData.height){s.size.height=s.parentData.height-r;if(q){s.size.width=s.size.height*s.aspectRatio}}},stop:function(e,m){var p=c(this).data("resizable"),f=p.options,k=p.position,l=p.containerOffset,d=p.containerPosition,g=p.containerElement;var i=c(p.helper),q=i.offset(),n=i.outerWidth()-p.sizeDiff.width,j=i.outerHeight()-p.sizeDiff.height;if(p._helper&&!f.animate&&(/relative/).test(g.css("position"))){c(this).css({left:q.left-d.left-l.left,width:n,height:j})}if(p._helper&&!f.animate&&(/static/).test(g.css("position"))){c(this).css({left:q.left-d.left-l.left,width:n,height:j})}}});c.ui.plugin.add("resizable","ghost",{start:function(f,g){var d=c(this).data("resizable"),h=d.options,e=d.size;d.ghost=d.originalElement.clone();d.ghost.css({opacity:0.25,display:"block",position:"relative",height:e.height,width:e.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof h.ghost=="string"?h.ghost:"");d.ghost.appendTo(d.helper)},resize:function(e,f){var d=c(this).data("resizable"),g=d.options;if(d.ghost){d.ghost.css({position:"relative",height:d.size.height,width:d.size.width})}},stop:function(e,f){var d=c(this).data("resizable"),g=d.options;if(d.ghost&&d.helper){d.helper.get(0).removeChild(d.ghost.get(0))}}});c.ui.plugin.add("resizable","grid",{resize:function(d,l){var n=c(this).data("resizable"),g=n.options,j=n.size,h=n.originalSize,i=n.originalPosition,m=n.axis,k=g._aspectRatio||d.shiftKey;g.grid=typeof g.grid=="number"?[g.grid,g.grid]:g.grid;var f=Math.round((j.width-h.width)/(g.grid[0]||1))*(g.grid[0]||1),e=Math.round((j.height-h.height)/(g.grid[1]||1))*(g.grid[1]||1);if(/^(se|s|e)$/.test(m)){n.size.width=h.width+f;n.size.height=h.height+e}else{if(/^(ne)$/.test(m)){n.size.width=h.width+f;n.size.height=h.height+e;n.position.top=i.top-e}else{if(/^(sw)$/.test(m)){n.size.width=h.width+f;n.size.height=h.height+e;n.position.left=i.left-f}else{n.size.width=h.width+f;n.size.height=h.height+e;n.position.top=i.top-e;n.position.left=i.left-f}}}}});var b=function(d){return parseInt(d,10)||0};var a=function(d){return !isNaN(parseInt(d,10))}})(jQuery);;/*
 * jQuery UI Selectable 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Selectables
 *
 * Depends:
 *	ui.core.js
 */
(function(a){a.widget("ui.selectable",a.extend({},a.ui.mouse,{_init:function(){var b=this;this.element.addClass("ui-selectable");this.dragged=false;var c;this.refresh=function(){c=a(b.options.filter,b.element[0]);c.each(function(){var d=a(this);var e=d.offset();a.data(this,"selectable-item",{element:this,$element:d,left:e.left,top:e.top,right:e.left+d.outerWidth(),bottom:e.top+d.outerHeight(),startselected:false,selected:d.hasClass("ui-selected"),selecting:d.hasClass("ui-selecting"),unselecting:d.hasClass("ui-unselecting")})})};this.refresh();this.selectees=c.addClass("ui-selectee");this._mouseInit();this.helper=a(document.createElement("div")).css({border:"1px dotted black"}).addClass("ui-selectable-helper")},destroy:function(){this.element.removeClass("ui-selectable ui-selectable-disabled").removeData("selectable").unbind(".selectable");this._mouseDestroy()},_mouseStart:function(d){var b=this;this.opos=[d.pageX,d.pageY];if(this.options.disabled){return}var c=this.options;this.selectees=a(c.filter,this.element[0]);this._trigger("start",d);a(c.appendTo).append(this.helper);this.helper.css({"z-index":100,position:"absolute",left:d.clientX,top:d.clientY,width:0,height:0});if(c.autoRefresh){this.refresh()}this.selectees.filter(".ui-selected").each(function(){var e=a.data(this,"selectable-item");e.startselected=true;if(!d.metaKey){e.$element.removeClass("ui-selected");e.selected=false;e.$element.addClass("ui-unselecting");e.unselecting=true;b._trigger("unselecting",d,{unselecting:e.element})}});a(d.target).parents().andSelf().each(function(){var e=a.data(this,"selectable-item");if(e){e.$element.removeClass("ui-unselecting").addClass("ui-selecting");e.unselecting=false;e.selecting=true;e.selected=true;b._trigger("selecting",d,{selecting:e.element});return false}})},_mouseDrag:function(i){var c=this;this.dragged=true;if(this.options.disabled){return}var e=this.options;var d=this.opos[0],h=this.opos[1],b=i.pageX,g=i.pageY;if(d>b){var f=b;b=d;d=f}if(h>g){var f=g;g=h;h=f}this.helper.css({left:d,top:h,width:b-d,height:g-h});this.selectees.each(function(){var j=a.data(this,"selectable-item");if(!j||j.element==c.element[0]){return}var k=false;if(e.tolerance=="touch"){k=(!(j.left>b||j.right<d||j.top>g||j.bottom<h))}else{if(e.tolerance=="fit"){k=(j.left>d&&j.right<b&&j.top>h&&j.bottom<g)}}if(k){if(j.selected){j.$element.removeClass("ui-selected");j.selected=false}if(j.unselecting){j.$element.removeClass("ui-unselecting");j.unselecting=false}if(!j.selecting){j.$element.addClass("ui-selecting");j.selecting=true;c._trigger("selecting",i,{selecting:j.element})}}else{if(j.selecting){if(i.metaKey&&j.startselected){j.$element.removeClass("ui-selecting");j.selecting=false;j.$element.addClass("ui-selected");j.selected=true}else{j.$element.removeClass("ui-selecting");j.selecting=false;if(j.startselected){j.$element.addClass("ui-unselecting");j.unselecting=true}c._trigger("unselecting",i,{unselecting:j.element})}}if(j.selected){if(!i.metaKey&&!j.startselected){j.$element.removeClass("ui-selected");j.selected=false;j.$element.addClass("ui-unselecting");j.unselecting=true;c._trigger("unselecting",i,{unselecting:j.element})}}}});return false},_mouseStop:function(d){var b=this;this.dragged=false;var c=this.options;a(".ui-unselecting",this.element[0]).each(function(){var e=a.data(this,"selectable-item");e.$element.removeClass("ui-unselecting");e.unselecting=false;e.startselected=false;b._trigger("unselected",d,{unselected:e.element})});a(".ui-selecting",this.element[0]).each(function(){var e=a.data(this,"selectable-item");e.$element.removeClass("ui-selecting").addClass("ui-selected");e.selecting=false;e.selected=true;e.startselected=true;b._trigger("selected",d,{selected:e.element})});this._trigger("stop",d);this.helper.remove();return false}}));a.extend(a.ui.selectable,{version:"1.7.2",defaults:{appendTo:"body",autoRefresh:true,cancel:":input,option",delay:0,distance:0,filter:"*",tolerance:"touch"}})})(jQuery);;/*
 * jQuery UI Sortable 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Sortables
 *
 * Depends:
 *	ui.core.js
 */
(function(a){a.widget("ui.sortable",a.extend({},a.ui.mouse,{_init:function(){var b=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?(/left|right/).test(this.items[0].item.css("float")):false;this.offset=this.element.offset();this._mouseInit()},destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").removeData("sortable").unbind(".sortable");this._mouseDestroy();for(var b=this.items.length-1;b>=0;b--){this.items[b].item.removeData("sortable-item")}},_mouseCapture:function(e,f){if(this.reverting){return false}if(this.options.disabled||this.options.type=="static"){return false}this._refreshItems(e);var d=null,c=this,b=a(e.target).parents().each(function(){if(a.data(this,"sortable-item")==c){d=a(this);return false}});if(a.data(e.target,"sortable-item")==c){d=a(e.target)}if(!d){return false}if(this.options.handle&&!f){var g=false;a(this.options.handle,d).find("*").andSelf().each(function(){if(this==e.target){g=true}});if(!g){return false}}this.currentItem=d;this._removeCurrentsFromItems();return true},_mouseStart:function(e,f,b){var g=this.options,c=this;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(e);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");a.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(e);this.originalPageX=e.pageX;this.originalPageY=e.pageY;if(g.cursorAt){this._adjustOffsetFromHelper(g.cursorAt)}this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};if(this.helper[0]!=this.currentItem[0]){this.currentItem.hide()}this._createPlaceholder();if(g.containment){this._setContainment()}if(g.cursor){if(a("body").css("cursor")){this._storedCursor=a("body").css("cursor")}a("body").css("cursor",g.cursor)}if(g.opacity){if(this.helper.css("opacity")){this._storedOpacity=this.helper.css("opacity")}this.helper.css("opacity",g.opacity)}if(g.zIndex){if(this.helper.css("zIndex")){this._storedZIndex=this.helper.css("zIndex")}this.helper.css("zIndex",g.zIndex)}if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){this.overflowOffset=this.scrollParent.offset()}this._trigger("start",e,this._uiHash());if(!this._preserveHelperProportions){this._cacheHelperProportions()}if(!b){for(var d=this.containers.length-1;d>=0;d--){this.containers[d]._trigger("activate",e,c._uiHash(this))}}if(a.ui.ddmanager){a.ui.ddmanager.current=this}if(a.ui.ddmanager&&!g.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,e)}this.dragging=true;this.helper.addClass("ui-sortable-helper");this._mouseDrag(e);return true},_mouseDrag:function(f){this.position=this._generatePosition(f);this.positionAbs=this._convertPositionTo("absolute");if(!this.lastPositionAbs){this.lastPositionAbs=this.positionAbs}if(this.options.scroll){var g=this.options,b=false;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){if((this.overflowOffset.top+this.scrollParent[0].offsetHeight)-f.pageY<g.scrollSensitivity){this.scrollParent[0].scrollTop=b=this.scrollParent[0].scrollTop+g.scrollSpeed}else{if(f.pageY-this.overflowOffset.top<g.scrollSensitivity){this.scrollParent[0].scrollTop=b=this.scrollParent[0].scrollTop-g.scrollSpeed}}if((this.overflowOffset.left+this.scrollParent[0].offsetWidth)-f.pageX<g.scrollSensitivity){this.scrollParent[0].scrollLeft=b=this.scrollParent[0].scrollLeft+g.scrollSpeed}else{if(f.pageX-this.overflowOffset.left<g.scrollSensitivity){this.scrollParent[0].scrollLeft=b=this.scrollParent[0].scrollLeft-g.scrollSpeed}}}else{if(f.pageY-a(document).scrollTop()<g.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()-g.scrollSpeed)}else{if(a(window).height()-(f.pageY-a(document).scrollTop())<g.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()+g.scrollSpeed)}}if(f.pageX-a(document).scrollLeft()<g.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()-g.scrollSpeed)}else{if(a(window).width()-(f.pageX-a(document).scrollLeft())<g.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()+g.scrollSpeed)}}}if(b!==false&&a.ui.ddmanager&&!g.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,f)}}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}for(var d=this.items.length-1;d>=0;d--){var e=this.items[d],c=e.item[0],h=this._intersectsWithPointer(e);if(!h){continue}if(c!=this.currentItem[0]&&this.placeholder[h==1?"next":"prev"]()[0]!=c&&!a.ui.contains(this.placeholder[0],c)&&(this.options.type=="semi-dynamic"?!a.ui.contains(this.element[0],c):true)){this.direction=h==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(e)){this._rearrange(f,e)}else{break}this._trigger("change",f,this._uiHash());break}}this._contactContainers(f);if(a.ui.ddmanager){a.ui.ddmanager.drag(this,f)}this._trigger("sort",f,this._uiHash());this.lastPositionAbs=this.positionAbs;return false},_mouseStop:function(c,d){if(!c){return}if(a.ui.ddmanager&&!this.options.dropBehaviour){a.ui.ddmanager.drop(this,c)}if(this.options.revert){var b=this;var e=b.placeholder.offset();b.reverting=true;a(this.helper).animate({left:e.left-this.offset.parent.left-b.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:e.top-this.offset.parent.top-b.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){b._clear(c)})}else{this._clear(c,d)}return false},cancel:function(){var b=this;if(this.dragging){this._mouseUp();if(this.options.helper=="original"){this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}for(var c=this.containers.length-1;c>=0;c--){this.containers[c]._trigger("deactivate",null,b._uiHash(this));if(this.containers[c].containerCache.over){this.containers[c]._trigger("out",null,b._uiHash(this));this.containers[c].containerCache.over=0}}}if(this.placeholder[0].parentNode){this.placeholder[0].parentNode.removeChild(this.placeholder[0])}if(this.options.helper!="original"&&this.helper&&this.helper[0].parentNode){this.helper.remove()}a.extend(this,{helper:null,dragging:false,reverting:false,_noFinalSort:null});if(this.domPosition.prev){a(this.domPosition.prev).after(this.currentItem)}else{a(this.domPosition.parent).prepend(this.currentItem)}return true},serialize:function(d){var b=this._getItemsAsjQuery(d&&d.connected);var c=[];d=d||{};a(b).each(function(){var e=(a(d.item||this).attr(d.attribute||"id")||"").match(d.expression||(/(.+)[-=_](.+)/));if(e){c.push((d.key||e[1]+"[]")+"="+(d.key&&d.expression?e[1]:e[2]))}});return c.join("&")},toArray:function(d){var b=this._getItemsAsjQuery(d&&d.connected);var c=[];d=d||{};b.each(function(){c.push(a(d.item||this).attr(d.attribute||"id")||"")});return c},_intersectsWith:function(m){var e=this.positionAbs.left,d=e+this.helperProportions.width,k=this.positionAbs.top,j=k+this.helperProportions.height;var f=m.left,c=f+m.width,n=m.top,i=n+m.height;var o=this.offset.click.top,h=this.offset.click.left;var g=(k+o)>n&&(k+o)<i&&(e+h)>f&&(e+h)<c;if(this.options.tolerance=="pointer"||this.options.forcePointerForContainers||(this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>m[this.floating?"width":"height"])){return g}else{return(f<e+(this.helperProportions.width/2)&&d-(this.helperProportions.width/2)<c&&n<k+(this.helperProportions.height/2)&&j-(this.helperProportions.height/2)<i)}},_intersectsWithPointer:function(d){var e=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,d.top,d.height),c=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,d.left,d.width),g=e&&c,b=this._getDragVerticalDirection(),f=this._getDragHorizontalDirection();if(!g){return false}return this.floating?(((f&&f=="right")||b=="down")?2:1):(b&&(b=="down"?2:1))},_intersectsWithSides:function(e){var c=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,e.top+(e.height/2),e.height),d=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,e.left+(e.width/2),e.width),b=this._getDragVerticalDirection(),f=this._getDragHorizontalDirection();if(this.floating&&f){return((f=="right"&&d)||(f=="left"&&!d))}else{return b&&((b=="down"&&c)||(b=="up"&&!c))}},_getDragVerticalDirection:function(){var b=this.positionAbs.top-this.lastPositionAbs.top;return b!=0&&(b>0?"down":"up")},_getDragHorizontalDirection:function(){var b=this.positionAbs.left-this.lastPositionAbs.left;return b!=0&&(b>0?"right":"left")},refresh:function(b){this._refreshItems(b);this.refreshPositions()},_connectWith:function(){var b=this.options;return b.connectWith.constructor==String?[b.connectWith]:b.connectWith},_getItemsAsjQuery:function(b){var l=this;var g=[];var e=[];var h=this._connectWith();if(h&&b){for(var d=h.length-1;d>=0;d--){var k=a(h[d]);for(var c=k.length-1;c>=0;c--){var f=a.data(k[c],"sortable");if(f&&f!=this&&!f.options.disabled){e.push([a.isFunction(f.options.items)?f.options.items.call(f.element):a(f.options.items,f.element).not(".ui-sortable-helper"),f])}}}}e.push([a.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):a(this.options.items,this.element).not(".ui-sortable-helper"),this]);for(var d=e.length-1;d>=0;d--){e[d][0].each(function(){g.push(this)})}return a(g)},_removeCurrentsFromItems:function(){var d=this.currentItem.find(":data(sortable-item)");for(var c=0;c<this.items.length;c++){for(var b=0;b<d.length;b++){if(d[b]==this.items[c].item[0]){this.items.splice(c,1)}}}},_refreshItems:function(b){this.items=[];this.containers=[this];var h=this.items;var p=this;var f=[[a.isFunction(this.options.items)?this.options.items.call(this.element[0],b,{item:this.currentItem}):a(this.options.items,this.element),this]];var l=this._connectWith();if(l){for(var e=l.length-1;e>=0;e--){var m=a(l[e]);for(var d=m.length-1;d>=0;d--){var g=a.data(m[d],"sortable");if(g&&g!=this&&!g.options.disabled){f.push([a.isFunction(g.options.items)?g.options.items.call(g.element[0],b,{item:this.currentItem}):a(g.options.items,g.element),g]);this.containers.push(g)}}}}for(var e=f.length-1;e>=0;e--){var k=f[e][1];var c=f[e][0];for(var d=0,n=c.length;d<n;d++){var o=a(c[d]);o.data("sortable-item",k);h.push({item:o,instance:k,width:0,height:0,left:0,top:0})}}},refreshPositions:function(b){if(this.offsetParent&&this.helper){this.offset.parent=this._getParentOffset()}for(var d=this.items.length-1;d>=0;d--){var e=this.items[d];if(e.instance!=this.currentContainer&&this.currentContainer&&e.item[0]!=this.currentItem[0]){continue}var c=this.options.toleranceElement?a(this.options.toleranceElement,e.item):e.item;if(!b){e.width=c.outerWidth();e.height=c.outerHeight()}var f=c.offset();e.left=f.left;e.top=f.top}if(this.options.custom&&this.options.custom.refreshContainers){this.options.custom.refreshContainers.call(this)}else{for(var d=this.containers.length-1;d>=0;d--){var f=this.containers[d].element.offset();this.containers[d].containerCache.left=f.left;this.containers[d].containerCache.top=f.top;this.containers[d].containerCache.width=this.containers[d].element.outerWidth();this.containers[d].containerCache.height=this.containers[d].element.outerHeight()}}},_createPlaceholder:function(d){var b=d||this,e=b.options;if(!e.placeholder||e.placeholder.constructor==String){var c=e.placeholder;e.placeholder={element:function(){var f=a(document.createElement(b.currentItem[0].nodeName)).addClass(c||b.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];if(!c){f.style.visibility="hidden"}return f},update:function(f,g){if(c&&!e.forcePlaceholderSize){return}if(!g.height()){g.height(b.currentItem.innerHeight()-parseInt(b.currentItem.css("paddingTop")||0,10)-parseInt(b.currentItem.css("paddingBottom")||0,10))}if(!g.width()){g.width(b.currentItem.innerWidth()-parseInt(b.currentItem.css("paddingLeft")||0,10)-parseInt(b.currentItem.css("paddingRight")||0,10))}}}}b.placeholder=a(e.placeholder.element.call(b.element,b.currentItem));b.currentItem.after(b.placeholder);e.placeholder.update(b,b.placeholder)},_contactContainers:function(d){for(var c=this.containers.length-1;c>=0;c--){if(this._intersectsWith(this.containers[c].containerCache)){if(!this.containers[c].containerCache.over){if(this.currentContainer!=this.containers[c]){var h=10000;var g=null;var e=this.positionAbs[this.containers[c].floating?"left":"top"];for(var b=this.items.length-1;b>=0;b--){if(!a.ui.contains(this.containers[c].element[0],this.items[b].item[0])){continue}var f=this.items[b][this.containers[c].floating?"left":"top"];if(Math.abs(f-e)<h){h=Math.abs(f-e);g=this.items[b]}}if(!g&&!this.options.dropOnEmpty){continue}this.currentContainer=this.containers[c];g?this._rearrange(d,g,null,true):this._rearrange(d,null,this.containers[c].element,true);this._trigger("change",d,this._uiHash());this.containers[c]._trigger("change",d,this._uiHash(this));this.options.placeholder.update(this.currentContainer,this.placeholder)}this.containers[c]._trigger("over",d,this._uiHash(this));this.containers[c].containerCache.over=1}}else{if(this.containers[c].containerCache.over){this.containers[c]._trigger("out",d,this._uiHash(this));this.containers[c].containerCache.over=0}}}},_createHelper:function(c){var d=this.options;var b=a.isFunction(d.helper)?a(d.helper.apply(this.element[0],[c,this.currentItem])):(d.helper=="clone"?this.currentItem.clone():this.currentItem);if(!b.parents("body").length){a(d.appendTo!="parent"?d.appendTo:this.currentItem[0].parentNode)[0].appendChild(b[0])}if(b[0]==this.currentItem[0]){this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}}if(b[0].style.width==""||d.forceHelperSize){b.width(this.currentItem.width())}if(b[0].style.height==""||d.forceHelperSize){b.height(this.currentItem.height())}return b},_adjustOffsetFromHelper:function(b){if(b.left!=undefined){this.offset.click.left=b.left+this.margins.left}if(b.right!=undefined){this.offset.click.left=this.helperProportions.width-b.right+this.margins.left}if(b.top!=undefined){this.offset.click.top=b.top+this.margins.top}if(b.bottom!=undefined){this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){b.left+=this.scrollParent.scrollLeft();b.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){b={top:0,left:0}}return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var b=this.currentItem.position();return{top:b.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:b.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.currentItem.css("marginLeft"),10)||0),top:(parseInt(this.currentItem.css("marginTop"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e=this.options;if(e.containment=="parent"){e.containment=this.helper[0].parentNode}if(e.containment=="document"||e.containment=="window"){this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(e.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(e.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(e.containment)){var c=a(e.containment)[0];var d=a(e.containment).offset();var b=(a(c).css("overflow")!="hidden");this.containment=[d.left+(parseInt(a(c).css("borderLeftWidth"),10)||0)+(parseInt(a(c).css("paddingLeft"),10)||0)-this.margins.left,d.top+(parseInt(a(c).css("borderTopWidth"),10)||0)+(parseInt(a(c).css("paddingTop"),10)||0)-this.margins.top,d.left+(b?Math.max(c.scrollWidth,c.offsetWidth):c.offsetWidth)-(parseInt(a(c).css("borderLeftWidth"),10)||0)-(parseInt(a(c).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,d.top+(b?Math.max(c.scrollHeight,c.offsetHeight):c.offsetHeight)-(parseInt(a(c).css("borderTopWidth"),10)||0)-(parseInt(a(c).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(f,h){if(!h){h=this.position}var c=f=="absolute"?1:-1;var e=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=(/(html|body)/i).test(b[0].tagName);return{top:(h.top+this.offset.relative.top*c+this.offset.parent.top*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(g?0:b.scrollTop()))*c)),left:(h.left+this.offset.relative.left*c+this.offset.parent.left*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:b.scrollLeft())*c))}},_generatePosition:function(e){var h=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,i=(/(html|body)/i).test(b[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0])){this.offset.relative=this._getRelativeOffset()}var d=e.pageX;var c=e.pageY;if(this.originalPosition){if(this.containment){if(e.pageX-this.offset.click.left<this.containment[0]){d=this.containment[0]+this.offset.click.left}if(e.pageY-this.offset.click.top<this.containment[1]){c=this.containment[1]+this.offset.click.top}if(e.pageX-this.offset.click.left>this.containment[2]){d=this.containment[2]+this.offset.click.left}if(e.pageY-this.offset.click.top>this.containment[3]){c=this.containment[3]+this.offset.click.top}}if(h.grid){var g=this.originalPageY+Math.round((c-this.originalPageY)/h.grid[1])*h.grid[1];c=this.containment?(!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:(!(g-this.offset.click.top<this.containment[1])?g-h.grid[1]:g+h.grid[1])):g;var f=this.originalPageX+Math.round((d-this.originalPageX)/h.grid[0])*h.grid[0];d=this.containment?(!(f-this.offset.click.left<this.containment[0]||f-this.offset.click.left>this.containment[2])?f:(!(f-this.offset.click.left<this.containment[0])?f-h.grid[0]:f+h.grid[0])):f}}return{top:(c-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(i?0:b.scrollTop())))),left:(d-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:b.scrollLeft())))}},_rearrange:function(g,f,c,e){c?c[0].appendChild(this.placeholder[0]):f.item[0].parentNode.insertBefore(this.placeholder[0],(this.direction=="down"?f.item[0]:f.item[0].nextSibling));this.counter=this.counter?++this.counter:1;var d=this,b=this.counter;window.setTimeout(function(){if(b==d.counter){d.refreshPositions(!e)}},0)},_clear:function(d,e){this.reverting=false;var f=[],b=this;if(!this._noFinalSort&&this.currentItem[0].parentNode){this.placeholder.before(this.currentItem)}this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var c in this._storedCSS){if(this._storedCSS[c]=="auto"||this._storedCSS[c]=="static"){this._storedCSS[c]=""}}this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}if(this.fromOutside&&!e){f.push(function(g){this._trigger("receive",g,this._uiHash(this.fromOutside))})}if((this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!e){f.push(function(g){this._trigger("update",g,this._uiHash())})}if(!a.ui.contains(this.element[0],this.currentItem[0])){if(!e){f.push(function(g){this._trigger("remove",g,this._uiHash())})}for(var c=this.containers.length-1;c>=0;c--){if(a.ui.contains(this.containers[c].element[0],this.currentItem[0])&&!e){f.push((function(g){return function(h){g._trigger("receive",h,this._uiHash(this))}}).call(this,this.containers[c]));f.push((function(g){return function(h){g._trigger("update",h,this._uiHash(this))}}).call(this,this.containers[c]))}}}for(var c=this.containers.length-1;c>=0;c--){if(!e){f.push((function(g){return function(h){g._trigger("deactivate",h,this._uiHash(this))}}).call(this,this.containers[c]))}if(this.containers[c].containerCache.over){f.push((function(g){return function(h){g._trigger("out",h,this._uiHash(this))}}).call(this,this.containers[c]));this.containers[c].containerCache.over=0}}if(this._storedCursor){a("body").css("cursor",this._storedCursor)}if(this._storedOpacity){this.helper.css("opacity",this._storedOpacity)}if(this._storedZIndex){this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex)}this.dragging=false;if(this.cancelHelperRemoval){if(!e){this._trigger("beforeStop",d,this._uiHash());for(var c=0;c<f.length;c++){f[c].call(this,d)}this._trigger("stop",d,this._uiHash())}return false}if(!e){this._trigger("beforeStop",d,this._uiHash())}this.placeholder[0].parentNode.removeChild(this.placeholder[0]);if(this.helper[0]!=this.currentItem[0]){this.helper.remove()}this.helper=null;if(!e){for(var c=0;c<f.length;c++){f[c].call(this,d)}this._trigger("stop",d,this._uiHash())}this.fromOutside=false;return true},_trigger:function(){if(a.widget.prototype._trigger.apply(this,arguments)===false){this.cancel()}},_uiHash:function(c){var b=c||this;return{helper:b.helper,placeholder:b.placeholder||a([]),position:b.position,absolutePosition:b.positionAbs,offset:b.positionAbs,item:b.currentItem,sender:c?c.element:null}}}));a.extend(a.ui.sortable,{getter:"serialize toArray",version:"1.7.2",eventPrefix:"sort",defaults:{appendTo:"parent",axis:false,cancel:":input,option",connectWith:false,containment:false,cursor:"auto",cursorAt:false,delay:0,distance:1,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:"> *",opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1000}})})(jQuery);;/*
 * jQuery UI Accordion 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Accordion
 *
 * Depends:
 *	ui.core.js
 */
(function(a){a.widget("ui.accordion",{_init:function(){var d=this.options,b=this;this.running=0;if(d.collapsible==a.ui.accordion.defaults.collapsible&&d.alwaysOpen!=a.ui.accordion.defaults.alwaysOpen){d.collapsible=!d.alwaysOpen}if(d.navigation){var c=this.element.find("a").filter(d.navigationFilter);if(c.length){if(c.filter(d.header).length){this.active=c}else{this.active=c.parent().parent().prev();c.addClass("ui-accordion-content-active")}}}this.element.addClass("ui-accordion ui-widget ui-helper-reset");if(this.element[0].nodeName=="UL"){this.element.children("li").addClass("ui-accordion-li-fix")}this.headers=this.element.find(d.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){a(this).addClass("ui-state-hover")}).bind("mouseleave.accordion",function(){a(this).removeClass("ui-state-hover")}).bind("focus.accordion",function(){a(this).addClass("ui-state-focus")}).bind("blur.accordion",function(){a(this).removeClass("ui-state-focus")});this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");this.active=this._findActive(this.active||d.active).toggleClass("ui-state-default").toggleClass("ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top");this.active.next().addClass("ui-accordion-content-active");a("<span/>").addClass("ui-icon "+d.icons.header).prependTo(this.headers);this.active.find(".ui-icon").toggleClass(d.icons.header).toggleClass(d.icons.headerSelected);if(a.browser.msie){this.element.find("a").css("zoom","1")}this.resize();this.element.attr("role","tablist");this.headers.attr("role","tab").bind("keydown",function(e){return b._keydown(e)}).next().attr("role","tabpanel");this.headers.not(this.active||"").attr("aria-expanded","false").attr("tabIndex","-1").next().hide();if(!this.active.length){this.headers.eq(0).attr("tabIndex","0")}else{this.active.attr("aria-expanded","true").attr("tabIndex","0")}if(!a.browser.safari){this.headers.find("a").attr("tabIndex","-1")}if(d.event){this.headers.bind((d.event)+".accordion",function(e){return b._clickHandler.call(b,e,this)})}},destroy:function(){var c=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role").unbind(".accordion").removeData("accordion");this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("tabindex");this.headers.find("a").removeAttr("tabindex");this.headers.children(".ui-icon").remove();var b=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active");if(c.autoHeight||c.fillHeight){b.css("height","")}},_setData:function(b,c){if(b=="alwaysOpen"){b="collapsible";c=!c}a.widget.prototype._setData.apply(this,arguments)},_keydown:function(e){var g=this.options,f=a.ui.keyCode;if(g.disabled||e.altKey||e.ctrlKey){return}var d=this.headers.length;var b=this.headers.index(e.target);var c=false;switch(e.keyCode){case f.RIGHT:case f.DOWN:c=this.headers[(b+1)%d];break;case f.LEFT:case f.UP:c=this.headers[(b-1+d)%d];break;case f.SPACE:case f.ENTER:return this._clickHandler({target:e.target},e.target)}if(c){a(e.target).attr("tabIndex","-1");a(c).attr("tabIndex","0");c.focus();return false}return true},resize:function(){var e=this.options,d;if(e.fillSpace){if(a.browser.msie){var b=this.element.parent().css("overflow");this.element.parent().css("overflow","hidden")}d=this.element.parent().height();if(a.browser.msie){this.element.parent().css("overflow",b)}this.headers.each(function(){d-=a(this).outerHeight()});var c=0;this.headers.next().each(function(){c=Math.max(c,a(this).innerHeight()-a(this).height())}).height(Math.max(0,d-c)).css("overflow","auto")}else{if(e.autoHeight){d=0;this.headers.next().each(function(){d=Math.max(d,a(this).outerHeight())}).height(d)}}},activate:function(b){var c=this._findActive(b)[0];this._clickHandler({target:c},c)},_findActive:function(b){return b?typeof b=="number"?this.headers.filter(":eq("+b+")"):this.headers.not(this.headers.not(b)):b===false?a([]):this.headers.filter(":eq(0)")},_clickHandler:function(b,f){var d=this.options;if(d.disabled){return false}if(!b.target&&d.collapsible){this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").find(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header);this.active.next().addClass("ui-accordion-content-active");var h=this.active.next(),e={options:d,newHeader:a([]),oldHeader:d.active,newContent:a([]),oldContent:h},c=(this.active=a([]));this._toggle(c,h,e);return false}var g=a(b.currentTarget||f);var i=g[0]==this.active[0];if(this.running||(!d.collapsible&&i)){return false}this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").find(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header);this.active.next().addClass("ui-accordion-content-active");if(!i){g.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").find(".ui-icon").removeClass(d.icons.header).addClass(d.icons.headerSelected);g.next().addClass("ui-accordion-content-active")}var c=g.next(),h=this.active.next(),e={options:d,newHeader:i&&d.collapsible?a([]):g,oldHeader:this.active,newContent:i&&d.collapsible?a([]):c.find("> *"),oldContent:h.find("> *")},j=this.headers.index(this.active[0])>this.headers.index(g[0]);this.active=i?a([]):g;this._toggle(c,h,e,i,j);return false},_toggle:function(b,i,g,j,k){var d=this.options,m=this;this.toShow=b;this.toHide=i;this.data=g;var c=function(){if(!m){return}return m._completed.apply(m,arguments)};this._trigger("changestart",null,this.data);this.running=i.size()===0?b.size():i.size();if(d.animated){var f={};if(d.collapsible&&j){f={toShow:a([]),toHide:i,complete:c,down:k,autoHeight:d.autoHeight||d.fillSpace}}else{f={toShow:b,toHide:i,complete:c,down:k,autoHeight:d.autoHeight||d.fillSpace}}if(!d.proxied){d.proxied=d.animated}if(!d.proxiedDuration){d.proxiedDuration=d.duration}d.animated=a.isFunction(d.proxied)?d.proxied(f):d.proxied;d.duration=a.isFunction(d.proxiedDuration)?d.proxiedDuration(f):d.proxiedDuration;var l=a.ui.accordion.animations,e=d.duration,h=d.animated;if(!l[h]){l[h]=function(n){this.slide(n,{easing:h,duration:e||700})}}l[h](f)}else{if(d.collapsible&&j){b.toggle()}else{i.hide();b.show()}c(true)}i.prev().attr("aria-expanded","false").attr("tabIndex","-1").blur();b.prev().attr("aria-expanded","true").attr("tabIndex","0").focus()},_completed:function(b){var c=this.options;this.running=b?0:--this.running;if(this.running){return}if(c.clearStyle){this.toShow.add(this.toHide).css({height:"",overflow:""})}this._trigger("change",null,this.data)}});a.extend(a.ui.accordion,{version:"1.7.2",defaults:{active:null,alwaysOpen:true,animated:"slide",autoHeight:true,clearStyle:false,collapsible:false,event:"click",fillSpace:false,header:"> li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:false,navigationFilter:function(){return this.href.toLowerCase()==location.href.toLowerCase()}},animations:{slide:function(j,h){j=a.extend({easing:"swing",duration:300},j,h);if(!j.toHide.size()){j.toShow.animate({height:"show"},j);return}if(!j.toShow.size()){j.toHide.animate({height:"hide"},j);return}var c=j.toShow.css("overflow"),g,d={},f={},e=["height","paddingTop","paddingBottom"],b;var i=j.toShow;b=i[0].style.width;i.width(parseInt(i.parent().width(),10)-parseInt(i.css("paddingLeft"),10)-parseInt(i.css("paddingRight"),10)-(parseInt(i.css("borderLeftWidth"),10)||0)-(parseInt(i.css("borderRightWidth"),10)||0));a.each(e,function(k,m){f[m]="hide";var l=(""+a.css(j.toShow[0],m)).match(/^([\d+-.]+)(.*)$/);d[m]={value:l[1],unit:l[2]||"px"}});j.toShow.css({height:0,overflow:"hidden"}).show();j.toHide.filter(":hidden").each(j.complete).end().filter(":visible").animate(f,{step:function(k,l){if(l.prop=="height"){g=(l.now-l.start)/(l.end-l.start)}j.toShow[0].style[l.prop]=(g*d[l.prop].value)+d[l.prop].unit},duration:j.duration,easing:j.easing,complete:function(){if(!j.autoHeight){j.toShow.css("height","")}j.toShow.css("width",b);j.toShow.css({overflow:c});j.complete()}})},bounceslide:function(b){this.slide(b,{easing:b.down?"easeOutBounce":"swing",duration:b.down?1000:200})},easeslide:function(b){this.slide(b,{easing:"easeinout",duration:700})}}})})(jQuery);;/*
 * jQuery UI Dialog 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Dialog
 *
 * Depends:
 *	ui.core.js
 *	ui.draggable.js
 *	ui.resizable.js
 */
(function(c){var b={dragStart:"start.draggable",drag:"drag.draggable",dragStop:"stop.draggable",maxHeight:"maxHeight.resizable",minHeight:"minHeight.resizable",maxWidth:"maxWidth.resizable",minWidth:"minWidth.resizable",resizeStart:"start.resizable",resize:"drag.resizable",resizeStop:"stop.resizable"},a="ui-dialog ui-widget ui-widget-content ui-corner-all ";c.widget("ui.dialog",{_init:function(){this.originalTitle=this.element.attr("title");var l=this,m=this.options,j=m.title||this.originalTitle||"&nbsp;",e=c.ui.dialog.getTitleId(this.element),k=(this.uiDialog=c("<div/>")).appendTo(document.body).hide().addClass(a+m.dialogClass).css({position:"absolute",overflow:"hidden",zIndex:m.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(n){(m.closeOnEscape&&n.keyCode&&n.keyCode==c.ui.keyCode.ESCAPE&&l.close(n))}).attr({role:"dialog","aria-labelledby":e}).mousedown(function(n){l.moveToTop(false,n)}),g=this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(k),f=(this.uiDialogTitlebar=c("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(k),i=c('<a href="#"/>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){i.addClass("ui-state-hover")},function(){i.removeClass("ui-state-hover")}).focus(function(){i.addClass("ui-state-focus")}).blur(function(){i.removeClass("ui-state-focus")}).mousedown(function(n){n.stopPropagation()}).click(function(n){l.close(n);return false}).appendTo(f),h=(this.uiDialogTitlebarCloseText=c("<span/>")).addClass("ui-icon ui-icon-closethick").text(m.closeText).appendTo(i),d=c("<span/>").addClass("ui-dialog-title").attr("id",e).html(j).prependTo(f);f.find("*").add(f).disableSelection();(m.draggable&&c.fn.draggable&&this._makeDraggable());(m.resizable&&c.fn.resizable&&this._makeResizable());this._createButtons(m.buttons);this._isOpen=false;(m.bgiframe&&c.fn.bgiframe&&k.bgiframe());(m.autoOpen&&this.open())},destroy:function(){(this.overlay&&this.overlay.destroy());this.uiDialog.hide();this.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body");this.uiDialog.remove();(this.originalTitle&&this.element.attr("title",this.originalTitle))},close:function(f){var d=this;if(false===d._trigger("beforeclose",f)){return}(d.overlay&&d.overlay.destroy());d.uiDialog.unbind("keypress.ui-dialog");(d.options.hide?d.uiDialog.hide(d.options.hide,function(){d._trigger("close",f)}):d.uiDialog.hide()&&d._trigger("close",f));c.ui.dialog.overlay.resize();d._isOpen=false;if(d.options.modal){var e=0;c(".ui-dialog").each(function(){if(this!=d.uiDialog[0]){e=Math.max(e,c(this).css("z-index"))}});c.ui.dialog.maxZ=e}},isOpen:function(){return this._isOpen},moveToTop:function(f,e){if((this.options.modal&&!f)||(!this.options.stack&&!this.options.modal)){return this._trigger("focus",e)}if(this.options.zIndex>c.ui.dialog.maxZ){c.ui.dialog.maxZ=this.options.zIndex}(this.overlay&&this.overlay.$el.css("z-index",c.ui.dialog.overlay.maxZ=++c.ui.dialog.maxZ));var d={scrollTop:this.element.attr("scrollTop"),scrollLeft:this.element.attr("scrollLeft")};this.uiDialog.css("z-index",++c.ui.dialog.maxZ);this.element.attr(d);this._trigger("focus",e)},open:function(){if(this._isOpen){return}var e=this.options,d=this.uiDialog;this.overlay=e.modal?new c.ui.dialog.overlay(this):null;(d.next().length&&d.appendTo("body"));this._size();this._position(e.position);d.show(e.show);this.moveToTop(true);(e.modal&&d.bind("keypress.ui-dialog",function(h){if(h.keyCode!=c.ui.keyCode.TAB){return}var g=c(":tabbable",this),i=g.filter(":first")[0],f=g.filter(":last")[0];if(h.target==f&&!h.shiftKey){setTimeout(function(){i.focus()},1)}else{if(h.target==i&&h.shiftKey){setTimeout(function(){f.focus()},1)}}}));c([]).add(d.find(".ui-dialog-content :tabbable:first")).add(d.find(".ui-dialog-buttonpane :tabbable:first")).add(d).filter(":first").focus();this._trigger("open");this._isOpen=true},_createButtons:function(g){var f=this,d=false,e=c("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix");this.uiDialog.find(".ui-dialog-buttonpane").remove();(typeof g=="object"&&g!==null&&c.each(g,function(){return !(d=true)}));if(d){c.each(g,function(h,i){c('<button type="button"></button>').addClass("ui-state-default ui-corner-all").text(h).click(function(){i.apply(f.element[0],arguments)}).hover(function(){c(this).addClass("ui-state-hover")},function(){c(this).removeClass("ui-state-hover")}).focus(function(){c(this).addClass("ui-state-focus")}).blur(function(){c(this).removeClass("ui-state-focus")}).appendTo(e)});e.appendTo(this.uiDialog)}},_makeDraggable:function(){var d=this,f=this.options,e;this.uiDialog.draggable({cancel:".ui-dialog-content",handle:".ui-dialog-titlebar",containment:"document",start:function(){e=f.height;c(this).height(c(this).height()).addClass("ui-dialog-dragging");(f.dragStart&&f.dragStart.apply(d.element[0],arguments))},drag:function(){(f.drag&&f.drag.apply(d.element[0],arguments))},stop:function(){c(this).removeClass("ui-dialog-dragging").height(e);(f.dragStop&&f.dragStop.apply(d.element[0],arguments));c.ui.dialog.overlay.resize()}})},_makeResizable:function(g){g=(g===undefined?this.options.resizable:g);var d=this,f=this.options,e=typeof g=="string"?g:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",alsoResize:this.element,maxWidth:f.maxWidth,maxHeight:f.maxHeight,minWidth:f.minWidth,minHeight:f.minHeight,start:function(){c(this).addClass("ui-dialog-resizing");(f.resizeStart&&f.resizeStart.apply(d.element[0],arguments))},resize:function(){(f.resize&&f.resize.apply(d.element[0],arguments))},handles:e,stop:function(){c(this).removeClass("ui-dialog-resizing");f.height=c(this).height();f.width=c(this).width();(f.resizeStop&&f.resizeStop.apply(d.element[0],arguments));c.ui.dialog.overlay.resize()}}).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_position:function(i){var e=c(window),f=c(document),g=f.scrollTop(),d=f.scrollLeft(),h=g;if(c.inArray(i,["center","top","right","bottom","left"])>=0){i=[i=="right"||i=="left"?i:"center",i=="top"||i=="bottom"?i:"middle"]}if(i.constructor!=Array){i=["center","middle"]}if(i[0].constructor==Number){d+=i[0]}else{switch(i[0]){case"left":d+=0;break;case"right":d+=e.width()-this.uiDialog.outerWidth();break;default:case"center":d+=(e.width()-this.uiDialog.outerWidth())/2}}if(i[1].constructor==Number){g+=i[1]}else{switch(i[1]){case"top":g+=0;break;case"bottom":g+=e.height()-this.uiDialog.outerHeight();break;default:case"middle":g+=(e.height()-this.uiDialog.outerHeight())/2}}g=Math.max(g,h);this.uiDialog.css({top:g,left:d})},_setData:function(e,f){(b[e]&&this.uiDialog.data(b[e],f));switch(e){case"buttons":this._createButtons(f);break;case"closeText":this.uiDialogTitlebarCloseText.text(f);break;case"dialogClass":this.uiDialog.removeClass(this.options.dialogClass).addClass(a+f);break;case"draggable":(f?this._makeDraggable():this.uiDialog.draggable("destroy"));break;case"height":this.uiDialog.height(f);break;case"position":this._position(f);break;case"resizable":var d=this.uiDialog,g=this.uiDialog.is(":data(resizable)");(g&&!f&&d.resizable("destroy"));(g&&typeof f=="string"&&d.resizable("option","handles",f));(g||this._makeResizable(f));break;case"title":c(".ui-dialog-title",this.uiDialogTitlebar).html(f||"&nbsp;");break;case"width":this.uiDialog.width(f);break}c.widget.prototype._setData.apply(this,arguments)},_size:function(){var e=this.options;this.element.css({height:0,minHeight:0,width:"auto"});var d=this.uiDialog.css({height:"auto",width:e.width}).height();this.element.css({minHeight:Math.max(e.minHeight-d,0),height:e.height=="auto"?"auto":Math.max(e.height-d,0)})}});c.extend(c.ui.dialog,{version:"1.7.2",defaults:{autoOpen:true,bgiframe:false,buttons:{},closeOnEscape:true,closeText:"close",dialogClass:"",draggable:true,hide:null,height:"auto",maxHeight:false,maxWidth:false,minHeight:150,minWidth:150,modal:false,position:"center",resizable:true,show:null,stack:true,title:"",width:300,zIndex:1000},getter:"isOpen",uuid:0,maxZ:0,getTitleId:function(d){return"ui-dialog-title-"+(d.attr("id")||++this.uuid)},overlay:function(d){this.$el=c.ui.dialog.overlay.create(d)}});c.extend(c.ui.dialog.overlay,{instances:[],maxZ:0,events:c.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(d){return d+".dialog-overlay"}).join(" "),create:function(e){if(this.instances.length===0){setTimeout(function(){if(c.ui.dialog.overlay.instances.length){c(document).bind(c.ui.dialog.overlay.events,function(f){var g=c(f.target).parents(".ui-dialog").css("zIndex")||0;return(g>c.ui.dialog.overlay.maxZ)})}},1);c(document).bind("keydown.dialog-overlay",function(f){(e.options.closeOnEscape&&f.keyCode&&f.keyCode==c.ui.keyCode.ESCAPE&&e.close(f))});c(window).bind("resize.dialog-overlay",c.ui.dialog.overlay.resize)}var d=c("<div></div>").appendTo(document.body).addClass("ui-widget-overlay").css({width:this.width(),height:this.height()});(e.options.bgiframe&&c.fn.bgiframe&&d.bgiframe());this.instances.push(d);return d},destroy:function(d){this.instances.splice(c.inArray(this.instances,d),1);if(this.instances.length===0){c([document,window]).unbind(".dialog-overlay")}d.remove();var e=0;c.each(this.instances,function(){e=Math.max(e,this.css("z-index"))});this.maxZ=e},height:function(){if(c.browser.msie&&c.browser.version<7){var e=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);var d=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight);if(e<d){return c(window).height()+"px"}else{return e+"px"}}else{return c(document).height()+"px"}},width:function(){if(c.browser.msie&&c.browser.version<7){var d=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);var e=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);if(d<e){return c(window).width()+"px"}else{return d+"px"}}else{return c(document).width()+"px"}},resize:function(){var d=c([]);c.each(c.ui.dialog.overlay.instances,function(){d=d.add(this)});d.css({width:0,height:0}).css({width:c.ui.dialog.overlay.width(),height:c.ui.dialog.overlay.height()})}});c.extend(c.ui.dialog.overlay.prototype,{destroy:function(){c.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);;/*
 * jQuery UI Slider 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	ui.core.js
 */
(function(a){a.widget("ui.slider",a.extend({},a.ui.mouse,{_init:function(){var b=this,c=this.options;this._keySliding=false;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all");this.range=a([]);if(c.range){if(c.range===true){this.range=a("<div></div>");if(!c.values){c.values=[this._valueMin(),this._valueMin()]}if(c.values.length&&c.values.length!=2){c.values=[c.values[0],c.values[0]]}}else{this.range=a("<div></div>")}this.range.appendTo(this.element).addClass("ui-slider-range");if(c.range=="min"||c.range=="max"){this.range.addClass("ui-slider-range-"+c.range)}this.range.addClass("ui-widget-header")}if(a(".ui-slider-handle",this.element).length==0){a('<a href="#"></a>').appendTo(this.element).addClass("ui-slider-handle")}if(c.values&&c.values.length){while(a(".ui-slider-handle",this.element).length<c.values.length){a('<a href="#"></a>').appendTo(this.element).addClass("ui-slider-handle")}}this.handles=a(".ui-slider-handle",this.element).addClass("ui-state-default ui-corner-all");this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(d){d.preventDefault()}).hover(function(){if(!c.disabled){a(this).addClass("ui-state-hover")}},function(){a(this).removeClass("ui-state-hover")}).focus(function(){if(!c.disabled){a(".ui-slider .ui-state-focus").removeClass("ui-state-focus");a(this).addClass("ui-state-focus")}else{a(this).blur()}}).blur(function(){a(this).removeClass("ui-state-focus")});this.handles.each(function(d){a(this).data("index.ui-slider-handle",d)});this.handles.keydown(function(i){var f=true;var e=a(this).data("index.ui-slider-handle");if(b.options.disabled){return}switch(i.keyCode){case a.ui.keyCode.HOME:case a.ui.keyCode.END:case a.ui.keyCode.UP:case a.ui.keyCode.RIGHT:case a.ui.keyCode.DOWN:case a.ui.keyCode.LEFT:f=false;if(!b._keySliding){b._keySliding=true;a(this).addClass("ui-state-active");b._start(i,e)}break}var g,d,h=b._step();if(b.options.values&&b.options.values.length){g=d=b.values(e)}else{g=d=b.value()}switch(i.keyCode){case a.ui.keyCode.HOME:d=b._valueMin();break;case a.ui.keyCode.END:d=b._valueMax();break;case a.ui.keyCode.UP:case a.ui.keyCode.RIGHT:if(g==b._valueMax()){return}d=g+h;break;case a.ui.keyCode.DOWN:case a.ui.keyCode.LEFT:if(g==b._valueMin()){return}d=g-h;break}b._slide(i,e,d);return f}).keyup(function(e){var d=a(this).data("index.ui-slider-handle");if(b._keySliding){b._stop(e,d);b._change(e,d);b._keySliding=false;a(this).removeClass("ui-state-active")}});this._refreshValue()},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider");this._mouseDestroy()},_mouseCapture:function(d){var e=this.options;if(e.disabled){return false}this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();var h={x:d.pageX,y:d.pageY};var j=this._normValueFromMouse(h);var c=this._valueMax()-this._valueMin()+1,f;var k=this,i;this.handles.each(function(l){var m=Math.abs(j-k.values(l));if(c>m){c=m;f=a(this);i=l}});if(e.range==true&&this.values(1)==e.min){f=a(this.handles[++i])}this._start(d,i);k._handleIndex=i;f.addClass("ui-state-active").focus();var g=f.offset();var b=!a(d.target).parents().andSelf().is(".ui-slider-handle");this._clickOffset=b?{left:0,top:0}:{left:d.pageX-g.left-(f.width()/2),top:d.pageY-g.top-(f.height()/2)-(parseInt(f.css("borderTopWidth"),10)||0)-(parseInt(f.css("borderBottomWidth"),10)||0)+(parseInt(f.css("marginTop"),10)||0)};j=this._normValueFromMouse(h);this._slide(d,i,j);return true},_mouseStart:function(b){return true},_mouseDrag:function(d){var b={x:d.pageX,y:d.pageY};var c=this._normValueFromMouse(b);this._slide(d,this._handleIndex,c);return false},_mouseStop:function(b){this.handles.removeClass("ui-state-active");this._stop(b,this._handleIndex);this._change(b,this._handleIndex);this._handleIndex=null;this._clickOffset=null;return false},_detectOrientation:function(){this.orientation=this.options.orientation=="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(d){var c,h;if("horizontal"==this.orientation){c=this.elementSize.width;h=d.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{c=this.elementSize.height;h=d.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}var f=(h/c);if(f>1){f=1}if(f<0){f=0}if("vertical"==this.orientation){f=1-f}var e=this._valueMax()-this._valueMin(),i=f*e,b=i%this.options.step,g=this._valueMin()+i-b;if(b>(this.options.step/2)){g+=this.options.step}return parseFloat(g.toFixed(5))},_start:function(d,c){var b={handle:this.handles[c],value:this.value()};if(this.options.values&&this.options.values.length){b.value=this.values(c);b.values=this.values()}this._trigger("start",d,b)},_slide:function(f,e,d){var g=this.handles[e];if(this.options.values&&this.options.values.length){var b=this.values(e?0:1);if((this.options.values.length==2&&this.options.range===true)&&((e==0&&d>b)||(e==1&&d<b))){d=b}if(d!=this.values(e)){var c=this.values();c[e]=d;var h=this._trigger("slide",f,{handle:this.handles[e],value:d,values:c});var b=this.values(e?0:1);if(h!==false){this.values(e,d,(f.type=="mousedown"&&this.options.animate),true)}}}else{if(d!=this.value()){var h=this._trigger("slide",f,{handle:this.handles[e],value:d});if(h!==false){this._setData("value",d,(f.type=="mousedown"&&this.options.animate))}}}},_stop:function(d,c){var b={handle:this.handles[c],value:this.value()};if(this.options.values&&this.options.values.length){b.value=this.values(c);b.values=this.values()}this._trigger("stop",d,b)},_change:function(d,c){var b={handle:this.handles[c],value:this.value()};if(this.options.values&&this.options.values.length){b.value=this.values(c);b.values=this.values()}this._trigger("change",d,b)},value:function(b){if(arguments.length){this._setData("value",b);this._change(null,0)}return this._value()},values:function(b,e,c,d){if(arguments.length>1){this.options.values[b]=e;this._refreshValue(c);if(!d){this._change(null,b)}}if(arguments.length){if(this.options.values&&this.options.values.length){return this._values(b)}else{return this.value()}}else{return this._values()}},_setData:function(b,d,c){a.widget.prototype._setData.apply(this,arguments);switch(b){case"disabled":if(d){this.handles.filter(".ui-state-focus").blur();this.handles.removeClass("ui-state-hover");this.handles.attr("disabled","disabled")}else{this.handles.removeAttr("disabled")}case"orientation":this._detectOrientation();this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation);this._refreshValue(c);break;case"value":this._refreshValue(c);break}},_step:function(){var b=this.options.step;return b},_value:function(){var b=this.options.value;if(b<this._valueMin()){b=this._valueMin()}if(b>this._valueMax()){b=this._valueMax()}return b},_values:function(b){if(arguments.length){var c=this.options.values[b];if(c<this._valueMin()){c=this._valueMin()}if(c>this._valueMax()){c=this._valueMax()}return c}else{return this.options.values}},_valueMin:function(){var b=this.options.min;return b},_valueMax:function(){var b=this.options.max;return b},_refreshValue:function(c){var f=this.options.range,d=this.options,l=this;if(this.options.values&&this.options.values.length){var i,h;this.handles.each(function(p,n){var o=(l.values(p)-l._valueMin())/(l._valueMax()-l._valueMin())*100;var m={};m[l.orientation=="horizontal"?"left":"bottom"]=o+"%";a(this).stop(1,1)[c?"animate":"css"](m,d.animate);if(l.options.range===true){if(l.orientation=="horizontal"){(p==0)&&l.range.stop(1,1)[c?"animate":"css"]({left:o+"%"},d.animate);(p==1)&&l.range[c?"animate":"css"]({width:(o-lastValPercent)+"%"},{queue:false,duration:d.animate})}else{(p==0)&&l.range.stop(1,1)[c?"animate":"css"]({bottom:(o)+"%"},d.animate);(p==1)&&l.range[c?"animate":"css"]({height:(o-lastValPercent)+"%"},{queue:false,duration:d.animate})}}lastValPercent=o})}else{var j=this.value(),g=this._valueMin(),k=this._valueMax(),e=k!=g?(j-g)/(k-g)*100:0;var b={};b[l.orientation=="horizontal"?"left":"bottom"]=e+"%";this.handle.stop(1,1)[c?"animate":"css"](b,d.animate);(f=="min")&&(this.orientation=="horizontal")&&this.range.stop(1,1)[c?"animate":"css"]({width:e+"%"},d.animate);(f=="max")&&(this.orientation=="horizontal")&&this.range[c?"animate":"css"]({width:(100-e)+"%"},{queue:false,duration:d.animate});(f=="min")&&(this.orientation=="vertical")&&this.range.stop(1,1)[c?"animate":"css"]({height:e+"%"},d.animate);(f=="max")&&(this.orientation=="vertical")&&this.range[c?"animate":"css"]({height:(100-e)+"%"},{queue:false,duration:d.animate})}}}));a.extend(a.ui.slider,{getter:"value values",version:"1.7.2",eventPrefix:"slide",defaults:{animate:false,delay:0,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null}})})(jQuery);;/*
 * jQuery UI Tabs 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Tabs
 *
 * Depends:
 *	ui.core.js
 */
(function(a){a.widget("ui.tabs",{_init:function(){if(this.options.deselectable!==undefined){this.options.collapsible=this.options.deselectable}this._tabify(true)},_setData:function(b,c){if(b=="selected"){if(this.options.collapsible&&c==this.options.selected){return}this.select(c)}else{this.options[b]=c;if(b=="deselectable"){this.options.collapsible=c}this._tabify()}},_tabId:function(b){return b.title&&b.title.replace(/\s/g,"_").replace(/[^A-Za-z0-9\-_:\.]/g,"")||this.options.idPrefix+a.data(b)},_sanitizeSelector:function(b){return b.replace(/:/g,"\\:")},_cookie:function(){var b=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+a.data(this.list[0]));return a.cookie.apply(null,[b].concat(a.makeArray(arguments)))},_ui:function(c,b){return{tab:c,panel:b,index:this.anchors.index(c)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var b=a(this);b.html(b.data("label.tabs")).removeData("label.tabs")})},_tabify:function(n){this.list=this.element.children("ul:first");this.lis=a("li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return a("a",this)[0]});this.panels=a([]);var p=this,d=this.options;var c=/^#.+/;this.anchors.each(function(r,o){var q=a(o).attr("href");var s=q.split("#")[0],u;if(s&&(s===location.toString().split("#")[0]||(u=a("base")[0])&&s===u.href)){q=o.hash;o.href=q}if(c.test(q)){p.panels=p.panels.add(p._sanitizeSelector(q))}else{if(q!="#"){a.data(o,"href.tabs",q);a.data(o,"load.tabs",q.replace(/#.*$/,""));var w=p._tabId(o);o.href="#"+w;var v=a("#"+w);if(!v.length){v=a(d.panelTemplate).attr("id",w).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(p.panels[r-1]||p.list);v.data("destroy.tabs",true)}p.panels=p.panels.add(v)}else{d.disabled.push(r)}}});if(n){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all");this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(d.selected===undefined){if(location.hash){this.anchors.each(function(q,o){if(o.hash==location.hash){d.selected=q;return false}})}if(typeof d.selected!="number"&&d.cookie){d.selected=parseInt(p._cookie(),10)}if(typeof d.selected!="number"&&this.lis.filter(".ui-tabs-selected").length){d.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))}d.selected=d.selected||0}else{if(d.selected===null){d.selected=-1}}d.selected=((d.selected>=0&&this.anchors[d.selected])||d.selected<0)?d.selected:0;d.disabled=a.unique(d.disabled.concat(a.map(this.lis.filter(".ui-state-disabled"),function(q,o){return p.lis.index(q)}))).sort();if(a.inArray(d.selected,d.disabled)!=-1){d.disabled.splice(a.inArray(d.selected,d.disabled),1)}this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active");if(d.selected>=0&&this.anchors.length){this.panels.eq(d.selected).removeClass("ui-tabs-hide");this.lis.eq(d.selected).addClass("ui-tabs-selected ui-state-active");p.element.queue("tabs",function(){p._trigger("show",null,p._ui(p.anchors[d.selected],p.panels[d.selected]))});this.load(d.selected)}a(window).bind("unload",function(){p.lis.add(p.anchors).unbind(".tabs");p.lis=p.anchors=p.panels=null})}else{d.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))}this.element[d.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible");if(d.cookie){this._cookie(d.selected,d.cookie)}for(var g=0,m;(m=this.lis[g]);g++){a(m)[a.inArray(g,d.disabled)!=-1&&!a(m).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled")}if(d.cache===false){this.anchors.removeData("cache.tabs")}this.lis.add(this.anchors).unbind(".tabs");if(d.event!="mouseover"){var f=function(o,i){if(i.is(":not(.ui-state-disabled)")){i.addClass("ui-state-"+o)}};var j=function(o,i){i.removeClass("ui-state-"+o)};this.lis.bind("mouseover.tabs",function(){f("hover",a(this))});this.lis.bind("mouseout.tabs",function(){j("hover",a(this))});this.anchors.bind("focus.tabs",function(){f("focus",a(this).closest("li"))});this.anchors.bind("blur.tabs",function(){j("focus",a(this).closest("li"))})}var b,h;if(d.fx){if(a.isArray(d.fx)){b=d.fx[0];h=d.fx[1]}else{b=h=d.fx}}function e(i,o){i.css({display:""});if(a.browser.msie&&o.opacity){i[0].style.removeAttribute("filter")}}var k=h?function(i,o){a(i).closest("li").removeClass("ui-state-default").addClass("ui-tabs-selected ui-state-active");o.hide().removeClass("ui-tabs-hide").animate(h,h.duration||"normal",function(){e(o,h);p._trigger("show",null,p._ui(i,o[0]))})}:function(i,o){a(i).closest("li").removeClass("ui-state-default").addClass("ui-tabs-selected ui-state-active");o.removeClass("ui-tabs-hide");p._trigger("show",null,p._ui(i,o[0]))};var l=b?function(o,i){i.animate(b,b.duration||"normal",function(){p.lis.removeClass("ui-tabs-selected ui-state-active").addClass("ui-state-default");i.addClass("ui-tabs-hide");e(i,b);p.element.dequeue("tabs")})}:function(o,i,q){p.lis.removeClass("ui-tabs-selected ui-state-active").addClass("ui-state-default");i.addClass("ui-tabs-hide");p.element.dequeue("tabs")};this.anchors.bind(d.event+".tabs",function(){var o=this,r=a(this).closest("li"),i=p.panels.filter(":not(.ui-tabs-hide)"),q=a(p._sanitizeSelector(this.hash));if((r.hasClass("ui-tabs-selected")&&!d.collapsible)||r.hasClass("ui-state-disabled")||r.hasClass("ui-state-processing")||p._trigger("select",null,p._ui(this,q[0]))===false){this.blur();return false}d.selected=p.anchors.index(this);p.abort();if(d.collapsible){if(r.hasClass("ui-tabs-selected")){d.selected=-1;if(d.cookie){p._cookie(d.selected,d.cookie)}p.element.queue("tabs",function(){l(o,i)}).dequeue("tabs");this.blur();return false}else{if(!i.length){if(d.cookie){p._cookie(d.selected,d.cookie)}p.element.queue("tabs",function(){k(o,q)});p.load(p.anchors.index(this));this.blur();return false}}}if(d.cookie){p._cookie(d.selected,d.cookie)}if(q.length){if(i.length){p.element.queue("tabs",function(){l(o,i)})}p.element.queue("tabs",function(){k(o,q)});p.load(p.anchors.index(this))}else{throw"jQuery UI Tabs: Mismatching fragment identifier."}if(a.browser.msie){this.blur()}});this.anchors.bind("click.tabs",function(){return false})},destroy:function(){var b=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var c=a.data(this,"href.tabs");if(c){this.href=c}var d=a(this).unbind(".tabs");a.each(["href","load","cache"],function(e,f){d.removeData(f+".tabs")})});this.lis.unbind(".tabs").add(this.panels).each(function(){if(a.data(this,"destroy.tabs")){a(this).remove()}else{a(this).removeClass(["ui-state-default","ui-corner-top","ui-tabs-selected","ui-state-active","ui-state-hover","ui-state-focus","ui-state-disabled","ui-tabs-panel","ui-widget-content","ui-corner-bottom","ui-tabs-hide"].join(" "))}});if(b.cookie){this._cookie(null,b.cookie)}},add:function(e,d,c){if(c===undefined){c=this.anchors.length}var b=this,g=this.options,i=a(g.tabTemplate.replace(/#\{href\}/g,e).replace(/#\{label\}/g,d)),h=!e.indexOf("#")?e.replace("#",""):this._tabId(a("a",i)[0]);i.addClass("ui-state-default ui-corner-top").data("destroy.tabs",true);var f=a("#"+h);if(!f.length){f=a(g.panelTemplate).attr("id",h).data("destroy.tabs",true)}f.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(c>=this.lis.length){i.appendTo(this.list);f.appendTo(this.list[0].parentNode)}else{i.insertBefore(this.lis[c]);f.insertBefore(this.panels[c])}g.disabled=a.map(g.disabled,function(k,j){return k>=c?++k:k});this._tabify();if(this.anchors.length==1){i.addClass("ui-tabs-selected ui-state-active");f.removeClass("ui-tabs-hide");this.element.queue("tabs",function(){b._trigger("show",null,b._ui(b.anchors[0],b.panels[0]))});this.load(0)}this._trigger("add",null,this._ui(this.anchors[c],this.panels[c]))},remove:function(b){var d=this.options,e=this.lis.eq(b).remove(),c=this.panels.eq(b).remove();if(e.hasClass("ui-tabs-selected")&&this.anchors.length>1){this.select(b+(b+1<this.anchors.length?1:-1))}d.disabled=a.map(a.grep(d.disabled,function(g,f){return g!=b}),function(g,f){return g>=b?--g:g});this._tabify();this._trigger("remove",null,this._ui(e.find("a")[0],c[0]))},enable:function(b){var c=this.options;if(a.inArray(b,c.disabled)==-1){return}this.lis.eq(b).removeClass("ui-state-disabled");c.disabled=a.grep(c.disabled,function(e,d){return e!=b});this._trigger("enable",null,this._ui(this.anchors[b],this.panels[b]))},disable:function(c){var b=this,d=this.options;if(c!=d.selected){this.lis.eq(c).addClass("ui-state-disabled");d.disabled.push(c);d.disabled.sort();this._trigger("disable",null,this._ui(this.anchors[c],this.panels[c]))}},select:function(b){if(typeof b=="string"){b=this.anchors.index(this.anchors.filter("[href$="+b+"]"))}else{if(b===null){b=-1}}if(b==-1&&this.options.collapsible){b=this.options.selected}this.anchors.eq(b).trigger(this.options.event+".tabs")},load:function(e){var c=this,g=this.options,b=this.anchors.eq(e)[0],d=a.data(b,"load.tabs");this.abort();if(!d||this.element.queue("tabs").length!==0&&a.data(b,"cache.tabs")){this.element.dequeue("tabs");return}this.lis.eq(e).addClass("ui-state-processing");if(g.spinner){var f=a("span",b);f.data("label.tabs",f.html()).html(g.spinner)}this.xhr=a.ajax(a.extend({},g.ajaxOptions,{url:d,success:function(i,h){a(c._sanitizeSelector(b.hash)).html(i);c._cleanup();if(g.cache){a.data(b,"cache.tabs",true)}c._trigger("load",null,c._ui(c.anchors[e],c.panels[e]));try{g.ajaxOptions.success(i,h)}catch(j){}c.element.dequeue("tabs")}}))},abort:function(){this.element.queue([]);this.panels.stop(false,true);if(this.xhr){this.xhr.abort();delete this.xhr}this._cleanup()},url:function(c,b){this.anchors.eq(c).removeData("cache.tabs").data("load.tabs",b)},length:function(){return this.anchors.length}});a.extend(a.ui.tabs,{version:"1.7.2",getter:"length",defaults:{ajaxOptions:null,cache:false,cookie:null,collapsible:false,disabled:[],event:"click",fx:null,idPrefix:"ui-tabs-",panelTemplate:"<div></div>",spinner:"<em>Loading&#8230;</em>",tabTemplate:'<li><a href="#{href}"><span>#{label}</span></a></li>'}});a.extend(a.ui.tabs.prototype,{rotation:null,rotate:function(d,f){var b=this,g=this.options;var c=b._rotate||(b._rotate=function(h){clearTimeout(b.rotation);b.rotation=setTimeout(function(){var i=g.selected;b.select(++i<b.anchors.length?i:0)},d);if(h){h.stopPropagation()}});var e=b._unrotate||(b._unrotate=!f?function(h){if(h.clientX){b.rotate(null)}}:function(h){t=g.selected;c()});if(d){this.element.bind("tabsshow",c);this.anchors.bind(g.event+".tabs",e);c()}else{clearTimeout(b.rotation);this.element.unbind("tabsshow",c);this.anchors.unbind(g.event+".tabs",e);delete this._rotate;delete this._unrotate}}})})(jQuery);;/*
 * jQuery UI Datepicker 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Datepicker
 *
 * Depends:
 *	ui.core.js
 */
(function($){$.extend($.ui,{datepicker:{version:"1.7.2"}});var PROP_NAME="datepicker";function Datepicker(){this.debug=false;this._curInst=null;this._keyEvent=false;this._disabledInputs=[];this._datepickerShowing=false;this._inDialog=false;this._mainDivId="ui-datepicker-div";this._inlineClass="ui-datepicker-inline";this._appendClass="ui-datepicker-append";this._triggerClass="ui-datepicker-trigger";this._dialogClass="ui-datepicker-dialog";this._disableClass="ui-datepicker-disabled";this._unselectableClass="ui-datepicker-unselectable";this._currentClass="ui-datepicker-current-day";this._dayOverClass="ui-datepicker-days-cell-over";this.regional=[];this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],dateFormat:"mm/dd/yy",firstDay:0,isRTL:false};this._defaults={showOn:"focus",showAnim:"show",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:false,hideIfNoPrevNext:false,navigationAsDateFormat:false,gotoCurrent:false,changeMonth:false,changeYear:false,showMonthAfterYear:false,yearRange:"-10:+10",showOtherMonths:false,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"normal",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:true,showButtonPanel:false};$.extend(this._defaults,this.regional[""]);this.dpDiv=$('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>')}$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",log:function(){if(this.debug){console.log.apply("",arguments)}},setDefaults:function(settings){extendRemove(this._defaults,settings||{});return this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(var attrName in this._defaults){var attrValue=target.getAttribute("date:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}var nodeName=target.nodeName.toLowerCase();var inline=(nodeName=="div"||nodeName=="span");if(!target.id){target.id="dp"+(++this.uuid)}var inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{},inlineSettings||{});if(nodeName=="input"){this._connectDatepicker(target,inst)}else{if(inline){this._inlineDatepicker(target,inst)}}},_newInst:function(target,inline){var id=target[0].id.replace(/([:\[\]\.])/g,"\\\\$1");return{id:id,input:target,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:inline,dpDiv:(!inline?this.dpDiv:$('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}},_connectDatepicker:function(target,inst){var input=$(target);inst.append=$([]);inst.trigger=$([]);if(input.hasClass(this.markerClassName)){return}var appendText=this._get(inst,"appendText");var isRTL=this._get(inst,"isRTL");if(appendText){inst.append=$('<span class="'+this._appendClass+'">'+appendText+"</span>");input[isRTL?"before":"after"](inst.append)}var showOn=this._get(inst,"showOn");if(showOn=="focus"||showOn=="both"){input.focus(this._showDatepicker)}if(showOn=="button"||showOn=="both"){var buttonText=this._get(inst,"buttonText");var buttonImage=this._get(inst,"buttonImage");inst.trigger=$(this._get(inst,"buttonImageOnly")?$("<img/>").addClass(this._triggerClass).attr({src:buttonImage,alt:buttonText,title:buttonText}):$('<button type="button"></button>').addClass(this._triggerClass).html(buttonImage==""?buttonText:$("<img/>").attr({src:buttonImage,alt:buttonText,title:buttonText})));input[isRTL?"before":"after"](inst.trigger);inst.trigger.click(function(){if($.datepicker._datepickerShowing&&$.datepicker._lastInput==target){$.datepicker._hideDatepicker()}else{$.datepicker._showDatepicker(target)}return false})}input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).bind("setData.datepicker",function(event,key,value){inst.settings[key]=value}).bind("getData.datepicker",function(event,key){return this._get(inst,key)});$.data(target,PROP_NAME,inst)},_inlineDatepicker:function(target,inst){var divSpan=$(target);if(divSpan.hasClass(this.markerClassName)){return}divSpan.addClass(this.markerClassName).append(inst.dpDiv).bind("setData.datepicker",function(event,key,value){inst.settings[key]=value}).bind("getData.datepicker",function(event,key){return this._get(inst,key)});$.data(target,PROP_NAME,inst);this._setDate(inst,this._getDefaultDate(inst));this._updateDatepicker(inst);this._updateAlternate(inst)},_dialogDatepicker:function(input,dateText,onSelect,settings,pos){var inst=this._dialogInst;if(!inst){var id="dp"+(++this.uuid);this._dialogInput=$('<input type="text" id="'+id+'" size="1" style="position: absolute; top: -100px;"/>');this._dialogInput.keydown(this._doKeyDown);$("body").append(this._dialogInput);inst=this._dialogInst=this._newInst(this._dialogInput,false);inst.settings={};$.data(this._dialogInput[0],PROP_NAME,inst)}extendRemove(inst.settings,settings||{});this._dialogInput.val(dateText);this._pos=(pos?(pos.length?pos:[pos.pageX,pos.pageY]):null);if(!this._pos){var browserWidth=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;var browserHeight=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;var scrollX=document.documentElement.scrollLeft||document.body.scrollLeft;var scrollY=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[(browserWidth/2)-100+scrollX,(browserHeight/2)-150+scrollY]}this._dialogInput.css("left",this._pos[0]+"px").css("top",this._pos[1]+"px");inst.settings.onSelect=onSelect;this._inDialog=true;this.dpDiv.addClass(this._dialogClass);this._showDatepicker(this._dialogInput[0]);if($.blockUI){$.blockUI(this.dpDiv)}$.data(this._dialogInput[0],PROP_NAME,inst);return this},_destroyDatepicker:function(target){var $target=$(target);var inst=$.data(target,PROP_NAME);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();$.removeData(target,PROP_NAME);if(nodeName=="input"){inst.append.remove();inst.trigger.remove();$target.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress)}else{if(nodeName=="div"||nodeName=="span"){$target.removeClass(this.markerClassName).empty()}}},_enableDatepicker:function(target){var $target=$(target);var inst=$.data(target,PROP_NAME);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();if(nodeName=="input"){target.disabled=false;inst.trigger.filter("button").each(function(){this.disabled=false}).end().filter("img").css({opacity:"1.0",cursor:""})}else{if(nodeName=="div"||nodeName=="span"){var inline=$target.children("."+this._inlineClass);inline.children().removeClass("ui-state-disabled")}}this._disabledInputs=$.map(this._disabledInputs,function(value){return(value==target?null:value)})},_disableDatepicker:function(target){var $target=$(target);var inst=$.data(target,PROP_NAME);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();if(nodeName=="input"){target.disabled=true;inst.trigger.filter("button").each(function(){this.disabled=true}).end().filter("img").css({opacity:"0.5",cursor:"default"})}else{if(nodeName=="div"||nodeName=="span"){var inline=$target.children("."+this._inlineClass);inline.children().addClass("ui-state-disabled")}}this._disabledInputs=$.map(this._disabledInputs,function(value){return(value==target?null:value)});this._disabledInputs[this._disabledInputs.length]=target},_isDisabledDatepicker:function(target){if(!target){return false}for(var i=0;i<this._disabledInputs.length;i++){if(this._disabledInputs[i]==target){return true}}return false},_getInst:function(target){try{return $.data(target,PROP_NAME)}catch(err){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(target,name,value){var inst=this._getInst(target);if(arguments.length==2&&typeof name=="string"){return(name=="defaults"?$.extend({},$.datepicker._defaults):(inst?(name=="all"?$.extend({},inst.settings):this._get(inst,name)):null))}var settings=name||{};if(typeof name=="string"){settings={};settings[name]=value}if(inst){if(this._curInst==inst){this._hideDatepicker(null)}var date=this._getDateDatepicker(target);extendRemove(inst.settings,settings);this._setDateDatepicker(target,date);this._updateDatepicker(inst)}},_changeDatepicker:function(target,name,value){this._optionDatepicker(target,name,value)},_refreshDatepicker:function(target){var inst=this._getInst(target);if(inst){this._updateDatepicker(inst)}},_setDateDatepicker:function(target,date,endDate){var inst=this._getInst(target);if(inst){this._setDate(inst,date,endDate);this._updateDatepicker(inst);this._updateAlternate(inst)}},_getDateDatepicker:function(target){var inst=this._getInst(target);if(inst&&!inst.inline){this._setDateFromField(inst)}return(inst?this._getDate(inst):null)},_doKeyDown:function(event){var inst=$.datepicker._getInst(event.target);var handled=true;var isRTL=inst.dpDiv.is(".ui-datepicker-rtl");inst._keyEvent=true;if($.datepicker._datepickerShowing){switch(event.keyCode){case 9:$.datepicker._hideDatepicker(null,"");break;case 13:var sel=$("td."+$.datepicker._dayOverClass+", td."+$.datepicker._currentClass,inst.dpDiv);if(sel[0]){$.datepicker._selectDay(event.target,inst.selectedMonth,inst.selectedYear,sel[0])}else{$.datepicker._hideDatepicker(null,$.datepicker._get(inst,"duration"))}return false;break;case 27:$.datepicker._hideDatepicker(null,$.datepicker._get(inst,"duration"));break;case 33:$.datepicker._adjustDate(event.target,(event.ctrlKey?-$.datepicker._get(inst,"stepBigMonths"):-$.datepicker._get(inst,"stepMonths")),"M");break;case 34:$.datepicker._adjustDate(event.target,(event.ctrlKey?+$.datepicker._get(inst,"stepBigMonths"):+$.datepicker._get(inst,"stepMonths")),"M");break;case 35:if(event.ctrlKey||event.metaKey){$.datepicker._clearDate(event.target)}handled=event.ctrlKey||event.metaKey;break;case 36:if(event.ctrlKey||event.metaKey){$.datepicker._gotoToday(event.target)}handled=event.ctrlKey||event.metaKey;break;case 37:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,(isRTL?+1:-1),"D")}handled=event.ctrlKey||event.metaKey;if(event.originalEvent.altKey){$.datepicker._adjustDate(event.target,(event.ctrlKey?-$.datepicker._get(inst,"stepBigMonths"):-$.datepicker._get(inst,"stepMonths")),"M")}break;case 38:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,-7,"D")}handled=event.ctrlKey||event.metaKey;break;case 39:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,(isRTL?-1:+1),"D")}handled=event.ctrlKey||event.metaKey;if(event.originalEvent.altKey){$.datepicker._adjustDate(event.target,(event.ctrlKey?+$.datepicker._get(inst,"stepBigMonths"):+$.datepicker._get(inst,"stepMonths")),"M")}break;case 40:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,+7,"D")}handled=event.ctrlKey||event.metaKey;break;default:handled=false}}else{if(event.keyCode==36&&event.ctrlKey){$.datepicker._showDatepicker(this)}else{handled=false}}if(handled){event.preventDefault();event.stopPropagation()}},_doKeyPress:function(event){var inst=$.datepicker._getInst(event.target);if($.datepicker._get(inst,"constrainInput")){var chars=$.datepicker._possibleChars($.datepicker._get(inst,"dateFormat"));var chr=String.fromCharCode(event.charCode==undefined?event.keyCode:event.charCode);return event.ctrlKey||(chr<" "||!chars||chars.indexOf(chr)>-1)}},_showDatepicker:function(input){input=input.target||input;if(input.nodeName.toLowerCase()!="input"){input=$("input",input.parentNode)[0]}if($.datepicker._isDisabledDatepicker(input)||$.datepicker._lastInput==input){return}var inst=$.datepicker._getInst(input);var beforeShow=$.datepicker._get(inst,"beforeShow");extendRemove(inst.settings,(beforeShow?beforeShow.apply(input,[input,inst]):{}));$.datepicker._hideDatepicker(null,"");$.datepicker._lastInput=input;$.datepicker._setDateFromField(inst);if($.datepicker._inDialog){input.value=""}if(!$.datepicker._pos){$.datepicker._pos=$.datepicker._findPos(input);$.datepicker._pos[1]+=input.offsetHeight}var isFixed=false;$(input).parents().each(function(){isFixed|=$(this).css("position")=="fixed";return !isFixed});if(isFixed&&$.browser.opera){$.datepicker._pos[0]-=document.documentElement.scrollLeft;$.datepicker._pos[1]-=document.documentElement.scrollTop}var offset={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null;inst.rangeStart=null;inst.dpDiv.css({position:"absolute",display:"block",top:"-1000px"});$.datepicker._updateDatepicker(inst);offset=$.datepicker._checkOffset(inst,offset,isFixed);inst.dpDiv.css({position:($.datepicker._inDialog&&$.blockUI?"static":(isFixed?"fixed":"absolute")),display:"none",left:offset.left+"px",top:offset.top+"px"});if(!inst.inline){var showAnim=$.datepicker._get(inst,"showAnim")||"show";var duration=$.datepicker._get(inst,"duration");var postProcess=function(){$.datepicker._datepickerShowing=true;if($.browser.msie&&parseInt($.browser.version,10)<7){$("iframe.ui-datepicker-cover").css({width:inst.dpDiv.width()+4,height:inst.dpDiv.height()+4})}};if($.effects&&$.effects[showAnim]){inst.dpDiv.show(showAnim,$.datepicker._get(inst,"showOptions"),duration,postProcess)}else{inst.dpDiv[showAnim](duration,postProcess)}if(duration==""){postProcess()}if(inst.input[0].type!="hidden"){inst.input[0].focus()}$.datepicker._curInst=inst}},_updateDatepicker:function(inst){var dims={width:inst.dpDiv.width()+4,height:inst.dpDiv.height()+4};var self=this;inst.dpDiv.empty().append(this._generateHTML(inst)).find("iframe.ui-datepicker-cover").css({width:dims.width,height:dims.height}).end().find("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a").bind("mouseout",function(){$(this).removeClass("ui-state-hover");if(this.className.indexOf("ui-datepicker-prev")!=-1){$(this).removeClass("ui-datepicker-prev-hover")}if(this.className.indexOf("ui-datepicker-next")!=-1){$(this).removeClass("ui-datepicker-next-hover")}}).bind("mouseover",function(){if(!self._isDisabledDatepicker(inst.inline?inst.dpDiv.parent()[0]:inst.input[0])){$(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");$(this).addClass("ui-state-hover");if(this.className.indexOf("ui-datepicker-prev")!=-1){$(this).addClass("ui-datepicker-prev-hover")}if(this.className.indexOf("ui-datepicker-next")!=-1){$(this).addClass("ui-datepicker-next-hover")}}}).end().find("."+this._dayOverClass+" a").trigger("mouseover").end();var numMonths=this._getNumberOfMonths(inst);var cols=numMonths[1];var width=17;if(cols>1){inst.dpDiv.addClass("ui-datepicker-multi-"+cols).css("width",(width*cols)+"em")}else{inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("")}inst.dpDiv[(numMonths[0]!=1||numMonths[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi");inst.dpDiv[(this._get(inst,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl");if(inst.input&&inst.input[0].type!="hidden"&&inst==$.datepicker._curInst){$(inst.input[0]).focus()}},_checkOffset:function(inst,offset,isFixed){var dpWidth=inst.dpDiv.outerWidth();var dpHeight=inst.dpDiv.outerHeight();var inputWidth=inst.input?inst.input.outerWidth():0;var inputHeight=inst.input?inst.input.outerHeight():0;var viewWidth=(window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth)+$(document).scrollLeft();var viewHeight=(window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight)+$(document).scrollTop();offset.left-=(this._get(inst,"isRTL")?(dpWidth-inputWidth):0);offset.left-=(isFixed&&offset.left==inst.input.offset().left)?$(document).scrollLeft():0;offset.top-=(isFixed&&offset.top==(inst.input.offset().top+inputHeight))?$(document).scrollTop():0;offset.left-=(offset.left+dpWidth>viewWidth&&viewWidth>dpWidth)?Math.abs(offset.left+dpWidth-viewWidth):0;offset.top-=(offset.top+dpHeight>viewHeight&&viewHeight>dpHeight)?Math.abs(offset.top+dpHeight+inputHeight*2-viewHeight):0;return offset},_findPos:function(obj){while(obj&&(obj.type=="hidden"||obj.nodeType!=1)){obj=obj.nextSibling}var position=$(obj).offset();return[position.left,position.top]},_hideDatepicker:function(input,duration){var inst=this._curInst;if(!inst||(input&&inst!=$.data(input,PROP_NAME))){return}if(inst.stayOpen){this._selectDate("#"+inst.id,this._formatDate(inst,inst.currentDay,inst.currentMonth,inst.currentYear))}inst.stayOpen=false;if(this._datepickerShowing){duration=(duration!=null?duration:this._get(inst,"duration"));var showAnim=this._get(inst,"showAnim");var postProcess=function(){$.datepicker._tidyDialog(inst)};if(duration!=""&&$.effects&&$.effects[showAnim]){inst.dpDiv.hide(showAnim,$.datepicker._get(inst,"showOptions"),duration,postProcess)}else{inst.dpDiv[(duration==""?"hide":(showAnim=="slideDown"?"slideUp":(showAnim=="fadeIn"?"fadeOut":"hide")))](duration,postProcess)}if(duration==""){this._tidyDialog(inst)}var onClose=this._get(inst,"onClose");if(onClose){onClose.apply((inst.input?inst.input[0]:null),[(inst.input?inst.input.val():""),inst])}this._datepickerShowing=false;this._lastInput=null;if(this._inDialog){this._dialogInput.css({position:"absolute",left:"0",top:"-100px"});if($.blockUI){$.unblockUI();$("body").append(this.dpDiv)}}this._inDialog=false}this._curInst=null},_tidyDialog:function(inst){inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(event){if(!$.datepicker._curInst){return}var $target=$(event.target);if(($target.parents("#"+$.datepicker._mainDivId).length==0)&&!$target.hasClass($.datepicker.markerClassName)&&!$target.hasClass($.datepicker._triggerClass)&&$.datepicker._datepickerShowing&&!($.datepicker._inDialog&&$.blockUI)){$.datepicker._hideDatepicker(null,"")}},_adjustDate:function(id,offset,period){var target=$(id);var inst=this._getInst(target[0]);if(this._isDisabledDatepicker(target[0])){return}this._adjustInstDate(inst,offset+(period=="M"?this._get(inst,"showCurrentAtPos"):0),period);this._updateDatepicker(inst)},_gotoToday:function(id){var target=$(id);var inst=this._getInst(target[0]);if(this._get(inst,"gotoCurrent")&&inst.currentDay){inst.selectedDay=inst.currentDay;inst.drawMonth=inst.selectedMonth=inst.currentMonth;inst.drawYear=inst.selectedYear=inst.currentYear}else{var date=new Date();inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear()}this._notifyChange(inst);this._adjustDate(target)},_selectMonthYear:function(id,select,period){var target=$(id);var inst=this._getInst(target[0]);inst._selectingMonthYear=false;inst["selected"+(period=="M"?"Month":"Year")]=inst["draw"+(period=="M"?"Month":"Year")]=parseInt(select.options[select.selectedIndex].value,10);this._notifyChange(inst);this._adjustDate(target)},_clickMonthYear:function(id){var target=$(id);var inst=this._getInst(target[0]);if(inst.input&&inst._selectingMonthYear&&!$.browser.msie){inst.input[0].focus()}inst._selectingMonthYear=!inst._selectingMonthYear},_selectDay:function(id,month,year,td){var target=$(id);if($(td).hasClass(this._unselectableClass)||this._isDisabledDatepicker(target[0])){return}var inst=this._getInst(target[0]);inst.selectedDay=inst.currentDay=$("a",td).html();inst.selectedMonth=inst.currentMonth=month;inst.selectedYear=inst.currentYear=year;if(inst.stayOpen){inst.endDay=inst.endMonth=inst.endYear=null}this._selectDate(id,this._formatDate(inst,inst.currentDay,inst.currentMonth,inst.currentYear));if(inst.stayOpen){inst.rangeStart=this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay));this._updateDatepicker(inst)}},_clearDate:function(id){var target=$(id);var inst=this._getInst(target[0]);inst.stayOpen=false;inst.endDay=inst.endMonth=inst.endYear=inst.rangeStart=null;this._selectDate(target,"")},_selectDate:function(id,dateStr){var target=$(id);var inst=this._getInst(target[0]);dateStr=(dateStr!=null?dateStr:this._formatDate(inst));if(inst.input){inst.input.val(dateStr)}this._updateAlternate(inst);var onSelect=this._get(inst,"onSelect");if(onSelect){onSelect.apply((inst.input?inst.input[0]:null),[dateStr,inst])}else{if(inst.input){inst.input.trigger("change")}}if(inst.inline){this._updateDatepicker(inst)}else{if(!inst.stayOpen){this._hideDatepicker(null,this._get(inst,"duration"));this._lastInput=inst.input[0];if(typeof(inst.input[0])!="object"){inst.input[0].focus()}this._lastInput=null}}},_updateAlternate:function(inst){var altField=this._get(inst,"altField");if(altField){var altFormat=this._get(inst,"altFormat")||this._get(inst,"dateFormat");var date=this._getDate(inst);dateStr=this.formatDate(altFormat,date,this._getFormatConfig(inst));$(altField).each(function(){$(this).val(dateStr)})}},noWeekends:function(date){var day=date.getDay();return[(day>0&&day<6),""]},iso8601Week:function(date){var checkDate=new Date(date.getFullYear(),date.getMonth(),date.getDate());var firstMon=new Date(checkDate.getFullYear(),1-1,4);var firstDay=firstMon.getDay()||7;firstMon.setDate(firstMon.getDate()+1-firstDay);if(firstDay<4&&checkDate<firstMon){checkDate.setDate(checkDate.getDate()-3);return $.datepicker.iso8601Week(checkDate)}else{if(checkDate>new Date(checkDate.getFullYear(),12-1,28)){firstDay=new Date(checkDate.getFullYear()+1,1-1,4).getDay()||7;if(firstDay>4&&(checkDate.getDay()||7)<firstDay-3){return 1}}}return Math.floor(((checkDate-firstMon)/86400000)/7)+1},parseDate:function(format,value,settings){if(format==null||value==null){throw"Invalid arguments"}value=(typeof value=="object"?value.toString():value+"");if(value==""){return null}var shortYearCutoff=(settings?settings.shortYearCutoff:null)||this._defaults.shortYearCutoff;var dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort;var dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames;var monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort;var monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames;var year=-1;var month=-1;var day=-1;var doy=-1;var literal=false;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};var getNumber=function(match){lookAhead(match);var origSize=(match=="@"?14:(match=="y"?4:(match=="o"?3:2)));var size=origSize;var num=0;while(size>0&&iValue<value.length&&value.charAt(iValue)>="0"&&value.charAt(iValue)<="9"){num=num*10+parseInt(value.charAt(iValue++),10);size--}if(size==origSize){throw"Missing number at position "+iValue}return num};var getName=function(match,shortNames,longNames){var names=(lookAhead(match)?longNames:shortNames);var size=0;for(var j=0;j<names.length;j++){size=Math.max(size,names[j].length)}var name="";var iInit=iValue;while(size>0&&iValue<value.length){name+=value.charAt(iValue++);for(var i=0;i<names.length;i++){if(name==names[i]){return i+1}}size--}throw"Unknown name at position "+iInit};var checkLiteral=function(){if(value.charAt(iValue)!=format.charAt(iFormat)){throw"Unexpected literal at position "+iValue}iValue++};var iValue=0;for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{checkLiteral()}}else{switch(format.charAt(iFormat)){case"d":day=getNumber("d");break;case"D":getName("D",dayNamesShort,dayNames);break;case"o":doy=getNumber("o");break;case"m":month=getNumber("m");break;case"M":month=getName("M",monthNamesShort,monthNames);break;case"y":year=getNumber("y");break;case"@":var date=new Date(getNumber("@"));year=date.getFullYear();month=date.getMonth()+1;day=date.getDate();break;case"'":if(lookAhead("'")){checkLiteral()}else{literal=true}break;default:checkLiteral()}}}if(year==-1){year=new Date().getFullYear()}else{if(year<100){year+=new Date().getFullYear()-new Date().getFullYear()%100+(year<=shortYearCutoff?0:-100)}}if(doy>-1){month=1;day=doy;do{var dim=this._getDaysInMonth(year,month-1);if(day<=dim){break}month++;day-=dim}while(true)}var date=this._daylightSavingAdjust(new Date(year,month-1,day));if(date.getFullYear()!=year||date.getMonth()+1!=month||date.getDate()!=day){throw"Invalid date"}return date},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TIMESTAMP:"@",W3C:"yy-mm-dd",formatDate:function(format,date,settings){if(!date){return""}var dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort;var dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames;var monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort;var monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};var formatNumber=function(match,value,len){var num=""+value;if(lookAhead(match)){while(num.length<len){num="0"+num}}return num};var formatName=function(match,value,shortNames,longNames){return(lookAhead(match)?longNames[value]:shortNames[value])};var output="";var literal=false;if(date){for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{output+=format.charAt(iFormat)}}else{switch(format.charAt(iFormat)){case"d":output+=formatNumber("d",date.getDate(),2);break;case"D":output+=formatName("D",date.getDay(),dayNamesShort,dayNames);break;case"o":var doy=date.getDate();for(var m=date.getMonth()-1;m>=0;m--){doy+=this._getDaysInMonth(date.getFullYear(),m)}output+=formatNumber("o",doy,3);break;case"m":output+=formatNumber("m",date.getMonth()+1,2);break;case"M":output+=formatName("M",date.getMonth(),monthNamesShort,monthNames);break;case"y":output+=(lookAhead("y")?date.getFullYear():(date.getYear()%100<10?"0":"")+date.getYear()%100);break;case"@":output+=date.getTime();break;case"'":if(lookAhead("'")){output+="'"}else{literal=true}break;default:output+=format.charAt(iFormat)}}}}return output},_possibleChars:function(format){var chars="";var literal=false;for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{chars+=format.charAt(iFormat)}}else{switch(format.charAt(iFormat)){case"d":case"m":case"y":case"@":chars+="0123456789";break;case"D":case"M":return null;case"'":if(lookAhead("'")){chars+="'"}else{literal=true}break;default:chars+=format.charAt(iFormat)}}}return chars},_get:function(inst,name){return inst.settings[name]!==undefined?inst.settings[name]:this._defaults[name]},_setDateFromField:function(inst){var dateFormat=this._get(inst,"dateFormat");var dates=inst.input?inst.input.val():null;inst.endDay=inst.endMonth=inst.endYear=null;var date=defaultDate=this._getDefaultDate(inst);var settings=this._getFormatConfig(inst);try{date=this.parseDate(dateFormat,dates,settings)||defaultDate}catch(event){this.log(event);date=defaultDate}inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear();inst.currentDay=(dates?date.getDate():0);inst.currentMonth=(dates?date.getMonth():0);inst.currentYear=(dates?date.getFullYear():0);this._adjustInstDate(inst)},_getDefaultDate:function(inst){var date=this._determineDate(this._get(inst,"defaultDate"),new Date());var minDate=this._getMinMaxDate(inst,"min",true);var maxDate=this._getMinMaxDate(inst,"max");date=(minDate&&date<minDate?minDate:date);date=(maxDate&&date>maxDate?maxDate:date);return date},_determineDate:function(date,defaultDate){var offsetNumeric=function(offset){var date=new Date();date.setDate(date.getDate()+offset);return date};var offsetString=function(offset,getDaysInMonth){var date=new Date();var year=date.getFullYear();var month=date.getMonth();var day=date.getDate();var pattern=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;var matches=pattern.exec(offset);while(matches){switch(matches[2]||"d"){case"d":case"D":day+=parseInt(matches[1],10);break;case"w":case"W":day+=parseInt(matches[1],10)*7;break;case"m":case"M":month+=parseInt(matches[1],10);day=Math.min(day,getDaysInMonth(year,month));break;case"y":case"Y":year+=parseInt(matches[1],10);day=Math.min(day,getDaysInMonth(year,month));break}matches=pattern.exec(offset)}return new Date(year,month,day)};date=(date==null?defaultDate:(typeof date=="string"?offsetString(date,this._getDaysInMonth):(typeof date=="number"?(isNaN(date)?defaultDate:offsetNumeric(date)):date)));date=(date&&date.toString()=="Invalid Date"?defaultDate:date);if(date){date.setHours(0);date.setMinutes(0);date.setSeconds(0);date.setMilliseconds(0)}return this._daylightSavingAdjust(date)},_daylightSavingAdjust:function(date){if(!date){return null}date.setHours(date.getHours()>12?date.getHours()+2:0);return date},_setDate:function(inst,date,endDate){var clear=!(date);var origMonth=inst.selectedMonth;var origYear=inst.selectedYear;date=this._determineDate(date,new Date());inst.selectedDay=inst.currentDay=date.getDate();inst.drawMonth=inst.selectedMonth=inst.currentMonth=date.getMonth();inst.drawYear=inst.selectedYear=inst.currentYear=date.getFullYear();if(origMonth!=inst.selectedMonth||origYear!=inst.selectedYear){this._notifyChange(inst)}this._adjustInstDate(inst);if(inst.input){inst.input.val(clear?"":this._formatDate(inst))}},_getDate:function(inst){var startDate=(!inst.currentYear||(inst.input&&inst.input.val()=="")?null:this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));return startDate},_generateHTML:function(inst){var today=new Date();today=this._daylightSavingAdjust(new Date(today.getFullYear(),today.getMonth(),today.getDate()));var isRTL=this._get(inst,"isRTL");var showButtonPanel=this._get(inst,"showButtonPanel");var hideIfNoPrevNext=this._get(inst,"hideIfNoPrevNext");var navigationAsDateFormat=this._get(inst,"navigationAsDateFormat");var numMonths=this._getNumberOfMonths(inst);var showCurrentAtPos=this._get(inst,"showCurrentAtPos");var stepMonths=this._get(inst,"stepMonths");var stepBigMonths=this._get(inst,"stepBigMonths");var isMultiMonth=(numMonths[0]!=1||numMonths[1]!=1);var currentDate=this._daylightSavingAdjust((!inst.currentDay?new Date(9999,9,9):new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));var minDate=this._getMinMaxDate(inst,"min",true);var maxDate=this._getMinMaxDate(inst,"max");var drawMonth=inst.drawMonth-showCurrentAtPos;var drawYear=inst.drawYear;if(drawMonth<0){drawMonth+=12;drawYear--}if(maxDate){var maxDraw=this._daylightSavingAdjust(new Date(maxDate.getFullYear(),maxDate.getMonth()-numMonths[1]+1,maxDate.getDate()));maxDraw=(minDate&&maxDraw<minDate?minDate:maxDraw);while(this._daylightSavingAdjust(new Date(drawYear,drawMonth,1))>maxDraw){drawMonth--;if(drawMonth<0){drawMonth=11;drawYear--}}}inst.drawMonth=drawMonth;inst.drawYear=drawYear;var prevText=this._get(inst,"prevText");prevText=(!navigationAsDateFormat?prevText:this.formatDate(prevText,this._daylightSavingAdjust(new Date(drawYear,drawMonth-stepMonths,1)),this._getFormatConfig(inst)));var prev=(this._canAdjustMonth(inst,-1,drawYear,drawMonth)?'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#'+inst.id+"', -"+stepMonths+", 'M');\" title=\""+prevText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"e":"w")+'">'+prevText+"</span></a>":(hideIfNoPrevNext?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+prevText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"e":"w")+'">'+prevText+"</span></a>"));var nextText=this._get(inst,"nextText");nextText=(!navigationAsDateFormat?nextText:this.formatDate(nextText,this._daylightSavingAdjust(new Date(drawYear,drawMonth+stepMonths,1)),this._getFormatConfig(inst)));var next=(this._canAdjustMonth(inst,+1,drawYear,drawMonth)?'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#'+inst.id+"', +"+stepMonths+", 'M');\" title=\""+nextText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"w":"e")+'">'+nextText+"</span></a>":(hideIfNoPrevNext?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+nextText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"w":"e")+'">'+nextText+"</span></a>"));var currentText=this._get(inst,"currentText");var gotoDate=(this._get(inst,"gotoCurrent")&&inst.currentDay?currentDate:today);currentText=(!navigationAsDateFormat?currentText:this.formatDate(currentText,gotoDate,this._getFormatConfig(inst)));var controls=(!inst.inline?'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery.datepicker._hideDatepicker();">'+this._get(inst,"closeText")+"</button>":"");var buttonPanel=(showButtonPanel)?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(isRTL?controls:"")+(this._isInRange(inst,gotoDate)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery.datepicker._gotoToday(\'#'+inst.id+"');\">"+currentText+"</button>":"")+(isRTL?"":controls)+"</div>":"";var firstDay=parseInt(this._get(inst,"firstDay"),10);firstDay=(isNaN(firstDay)?0:firstDay);var dayNames=this._get(inst,"dayNames");var dayNamesShort=this._get(inst,"dayNamesShort");var dayNamesMin=this._get(inst,"dayNamesMin");var monthNames=this._get(inst,"monthNames");var monthNamesShort=this._get(inst,"monthNamesShort");var beforeShowDay=this._get(inst,"beforeShowDay");var showOtherMonths=this._get(inst,"showOtherMonths");var calculateWeek=this._get(inst,"calculateWeek")||this.iso8601Week;var endDate=inst.endDay?this._daylightSavingAdjust(new Date(inst.endYear,inst.endMonth,inst.endDay)):currentDate;var defaultDate=this._getDefaultDate(inst);var html="";for(var row=0;row<numMonths[0];row++){var group="";for(var col=0;col<numMonths[1];col++){var selectedDate=this._daylightSavingAdjust(new Date(drawYear,drawMonth,inst.selectedDay));var cornerClass=" ui-corner-all";var calender="";if(isMultiMonth){calender+='<div class="ui-datepicker-group ui-datepicker-group-';switch(col){case 0:calender+="first";cornerClass=" ui-corner-"+(isRTL?"right":"left");break;case numMonths[1]-1:calender+="last";cornerClass=" ui-corner-"+(isRTL?"left":"right");break;default:calender+="middle";cornerClass="";break}calender+='">'}calender+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+cornerClass+'">'+(/all|left/.test(cornerClass)&&row==0?(isRTL?next:prev):"")+(/all|right/.test(cornerClass)&&row==0?(isRTL?prev:next):"")+this._generateMonthYearHeader(inst,drawMonth,drawYear,minDate,maxDate,selectedDate,row>0||col>0,monthNames,monthNamesShort)+'</div><table class="ui-datepicker-calendar"><thead><tr>';var thead="";for(var dow=0;dow<7;dow++){var day=(dow+firstDay)%7;thead+="<th"+((dow+firstDay+6)%7>=5?' class="ui-datepicker-week-end"':"")+'><span title="'+dayNames[day]+'">'+dayNamesMin[day]+"</span></th>"}calender+=thead+"</tr></thead><tbody>";var daysInMonth=this._getDaysInMonth(drawYear,drawMonth);if(drawYear==inst.selectedYear&&drawMonth==inst.selectedMonth){inst.selectedDay=Math.min(inst.selectedDay,daysInMonth)}var leadDays=(this._getFirstDayOfMonth(drawYear,drawMonth)-firstDay+7)%7;var numRows=(isMultiMonth?6:Math.ceil((leadDays+daysInMonth)/7));var printDate=this._daylightSavingAdjust(new Date(drawYear,drawMonth,1-leadDays));for(var dRow=0;dRow<numRows;dRow++){calender+="<tr>";var tbody="";for(var dow=0;dow<7;dow++){var daySettings=(beforeShowDay?beforeShowDay.apply((inst.input?inst.input[0]:null),[printDate]):[true,""]);var otherMonth=(printDate.getMonth()!=drawMonth);var unselectable=otherMonth||!daySettings[0]||(minDate&&printDate<minDate)||(maxDate&&printDate>maxDate);tbody+='<td class="'+((dow+firstDay+6)%7>=5?" ui-datepicker-week-end":"")+(otherMonth?" ui-datepicker-other-month":"")+((printDate.getTime()==selectedDate.getTime()&&drawMonth==inst.selectedMonth&&inst._keyEvent)||(defaultDate.getTime()==printDate.getTime()&&defaultDate.getTime()==selectedDate.getTime())?" "+this._dayOverClass:"")+(unselectable?" "+this._unselectableClass+" ui-state-disabled":"")+(otherMonth&&!showOtherMonths?"":" "+daySettings[1]+(printDate.getTime()>=currentDate.getTime()&&printDate.getTime()<=endDate.getTime()?" "+this._currentClass:"")+(printDate.getTime()==today.getTime()?" ui-datepicker-today":""))+'"'+((!otherMonth||showOtherMonths)&&daySettings[2]?' title="'+daySettings[2]+'"':"")+(unselectable?"":" onclick=\"DP_jQuery.datepicker._selectDay('#"+inst.id+"',"+drawMonth+","+drawYear+', this);return false;"')+">"+(otherMonth?(showOtherMonths?printDate.getDate():"&#xa0;"):(unselectable?'<span class="ui-state-default">'+printDate.getDate()+"</span>":'<a class="ui-state-default'+(printDate.getTime()==today.getTime()?" ui-state-highlight":"")+(printDate.getTime()>=currentDate.getTime()&&printDate.getTime()<=endDate.getTime()?" ui-state-active":"")+'" href="#">'+printDate.getDate()+"</a>"))+"</td>";printDate.setDate(printDate.getDate()+1);printDate=this._daylightSavingAdjust(printDate)}calender+=tbody+"</tr>"}drawMonth++;if(drawMonth>11){drawMonth=0;drawYear++}calender+="</tbody></table>"+(isMultiMonth?"</div>"+((numMonths[0]>0&&col==numMonths[1]-1)?'<div class="ui-datepicker-row-break"></div>':""):"");group+=calender}html+=group}html+=buttonPanel+($.browser.msie&&parseInt($.browser.version,10)<7&&!inst.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':"");inst._keyEvent=false;return html},_generateMonthYearHeader:function(inst,drawMonth,drawYear,minDate,maxDate,selectedDate,secondary,monthNames,monthNamesShort){minDate=(inst.rangeStart&&minDate&&selectedDate<minDate?selectedDate:minDate);var changeMonth=this._get(inst,"changeMonth");var changeYear=this._get(inst,"changeYear");var showMonthAfterYear=this._get(inst,"showMonthAfterYear");var html='<div class="ui-datepicker-title">';var monthHtml="";if(secondary||!changeMonth){monthHtml+='<span class="ui-datepicker-month">'+monthNames[drawMonth]+"</span> "}else{var inMinYear=(minDate&&minDate.getFullYear()==drawYear);var inMaxYear=(maxDate&&maxDate.getFullYear()==drawYear);monthHtml+='<select class="ui-datepicker-month" onchange="DP_jQuery.datepicker._selectMonthYear(\'#'+inst.id+"', this, 'M');\" onclick=\"DP_jQuery.datepicker._clickMonthYear('#"+inst.id+"');\">";for(var month=0;month<12;month++){if((!inMinYear||month>=minDate.getMonth())&&(!inMaxYear||month<=maxDate.getMonth())){monthHtml+='<option value="'+month+'"'+(month==drawMonth?' selected="selected"':"")+">"+monthNamesShort[month]+"</option>"}}monthHtml+="</select>"}if(!showMonthAfterYear){html+=monthHtml+((secondary||changeMonth||changeYear)&&(!(changeMonth&&changeYear))?"&#xa0;":"")}if(secondary||!changeYear){html+='<span class="ui-datepicker-year">'+drawYear+"</span>"}else{var years=this._get(inst,"yearRange").split(":");var year=0;var endYear=0;if(years.length!=2){year=drawYear-10;endYear=drawYear+10}else{if(years[0].charAt(0)=="+"||years[0].charAt(0)=="-"){year=drawYear+parseInt(years[0],10);endYear=drawYear+parseInt(years[1],10)}else{year=parseInt(years[0],10);endYear=parseInt(years[1],10)}}year=(minDate?Math.max(year,minDate.getFullYear()):year);endYear=(maxDate?Math.min(endYear,maxDate.getFullYear()):endYear);html+='<select class="ui-datepicker-year" onchange="DP_jQuery.datepicker._selectMonthYear(\'#'+inst.id+"', this, 'Y');\" onclick=\"DP_jQuery.datepicker._clickMonthYear('#"+inst.id+"');\">";for(;year<=endYear;year++){html+='<option value="'+year+'"'+(year==drawYear?' selected="selected"':"")+">"+year+"</option>"}html+="</select>"}if(showMonthAfterYear){html+=(secondary||changeMonth||changeYear?"&#xa0;":"")+monthHtml}html+="</div>";return html},_adjustInstDate:function(inst,offset,period){var year=inst.drawYear+(period=="Y"?offset:0);var month=inst.drawMonth+(period=="M"?offset:0);var day=Math.min(inst.selectedDay,this._getDaysInMonth(year,month))+(period=="D"?offset:0);var date=this._daylightSavingAdjust(new Date(year,month,day));var minDate=this._getMinMaxDate(inst,"min",true);var maxDate=this._getMinMaxDate(inst,"max");date=(minDate&&date<minDate?minDate:date);date=(maxDate&&date>maxDate?maxDate:date);inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear();if(period=="M"||period=="Y"){this._notifyChange(inst)}},_notifyChange:function(inst){var onChange=this._get(inst,"onChangeMonthYear");if(onChange){onChange.apply((inst.input?inst.input[0]:null),[inst.selectedYear,inst.selectedMonth+1,inst])}},_getNumberOfMonths:function(inst){var numMonths=this._get(inst,"numberOfMonths");return(numMonths==null?[1,1]:(typeof numMonths=="number"?[1,numMonths]:numMonths))},_getMinMaxDate:function(inst,minMax,checkRange){var date=this._determineDate(this._get(inst,minMax+"Date"),null);return(!checkRange||!inst.rangeStart?date:(!date||inst.rangeStart>date?inst.rangeStart:date))},_getDaysInMonth:function(year,month){return 32-new Date(year,month,32).getDate()},_getFirstDayOfMonth:function(year,month){return new Date(year,month,1).getDay()},_canAdjustMonth:function(inst,offset,curYear,curMonth){var numMonths=this._getNumberOfMonths(inst);var date=this._daylightSavingAdjust(new Date(curYear,curMonth+(offset<0?offset:numMonths[1]),1));if(offset<0){date.setDate(this._getDaysInMonth(date.getFullYear(),date.getMonth()))}return this._isInRange(inst,date)},_isInRange:function(inst,date){var newMinDate=(!inst.rangeStart?null:this._daylightSavingAdjust(new Date(inst.selectedYear,inst.selectedMonth,inst.selectedDay)));newMinDate=(newMinDate&&inst.rangeStart<newMinDate?inst.rangeStart:newMinDate);var minDate=newMinDate||this._getMinMaxDate(inst,"min");var maxDate=this._getMinMaxDate(inst,"max");return((!minDate||date>=minDate)&&(!maxDate||date<=maxDate))},_getFormatConfig:function(inst){var shortYearCutoff=this._get(inst,"shortYearCutoff");shortYearCutoff=(typeof shortYearCutoff!="string"?shortYearCutoff:new Date().getFullYear()%100+parseInt(shortYearCutoff,10));return{shortYearCutoff:shortYearCutoff,dayNamesShort:this._get(inst,"dayNamesShort"),dayNames:this._get(inst,"dayNames"),monthNamesShort:this._get(inst,"monthNamesShort"),monthNames:this._get(inst,"monthNames")}},_formatDate:function(inst,day,month,year){if(!day){inst.currentDay=inst.selectedDay;inst.currentMonth=inst.selectedMonth;inst.currentYear=inst.selectedYear}var date=(day?(typeof day=="object"?day:this._daylightSavingAdjust(new Date(year,month,day))):this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));return this.formatDate(this._get(inst,"dateFormat"),date,this._getFormatConfig(inst))}});function extendRemove(target,props){$.extend(target,props);for(var name in props){if(props[name]==null||props[name]==undefined){target[name]=props[name]}}return target}function isArray(a){return(a&&(($.browser.safari&&typeof a=="object"&&a.length)||(a.constructor&&a.constructor.toString().match(/\Array\(\)/))))}$.fn.datepicker=function(options){if(!$.datepicker.initialized){$(document).mousedown($.datepicker._checkExternalClick).find("body").append($.datepicker.dpDiv);$.datepicker.initialized=true}var otherArgs=Array.prototype.slice.call(arguments,1);if(typeof options=="string"&&(options=="isDisabled"||options=="getDate")){return $.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this[0]].concat(otherArgs))}if(options=="option"&&arguments.length==2&&typeof arguments[1]=="string"){return $.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this[0]].concat(otherArgs))}return this.each(function(){typeof options=="string"?$.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this].concat(otherArgs)):$.datepicker._attachDatepicker(this,options)})};$.datepicker=new Datepicker();$.datepicker.initialized=false;$.datepicker.uuid=new Date().getTime();$.datepicker.version="1.7.2";window.DP_jQuery=$})(jQuery);;/*
 * jQuery UI Progressbar 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Progressbar
 *
 * Depends:
 *   ui.core.js
 */
(function(a){a.widget("ui.progressbar",{_init:function(){this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this._valueMin(),"aria-valuemax":this._valueMax(),"aria-valuenow":this._value()});this.valueDiv=a('<div class="ui-progressbar-value ui-widget-header ui-corner-left"></div>').appendTo(this.element);this._refreshValue()},destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow").removeData("progressbar").unbind(".progressbar");this.valueDiv.remove();a.widget.prototype.destroy.apply(this,arguments)},value:function(b){if(b===undefined){return this._value()}this._setData("value",b);return this},_setData:function(b,c){switch(b){case"value":this.options.value=c;this._refreshValue();this._trigger("change",null,{});break}a.widget.prototype._setData.apply(this,arguments)},_value:function(){var b=this.options.value;if(b<this._valueMin()){b=this._valueMin()}if(b>this._valueMax()){b=this._valueMax()}return b},_valueMin:function(){var b=0;return b},_valueMax:function(){var b=100;return b},_refreshValue:function(){var b=this.value();this.valueDiv[b==this._valueMax()?"addClass":"removeClass"]("ui-corner-right");this.valueDiv.width(b+"%");this.element.attr("aria-valuenow",b)}});a.extend(a.ui.progressbar,{version:"1.7.2",defaults:{value:0}})})(jQuery);;/*
 * jQuery UI Effects 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/
 */
jQuery.effects||(function(d){d.effects={version:"1.7.2",save:function(g,h){for(var f=0;f<h.length;f++){if(h[f]!==null){g.data("ec.storage."+h[f],g[0].style[h[f]])}}},restore:function(g,h){for(var f=0;f<h.length;f++){if(h[f]!==null){g.css(h[f],g.data("ec.storage."+h[f]))}}},setMode:function(f,g){if(g=="toggle"){g=f.is(":hidden")?"show":"hide"}return g},getBaseline:function(g,h){var i,f;switch(g[0]){case"top":i=0;break;case"middle":i=0.5;break;case"bottom":i=1;break;default:i=g[0]/h.height}switch(g[1]){case"left":f=0;break;case"center":f=0.5;break;case"right":f=1;break;default:f=g[1]/h.width}return{x:f,y:i}},createWrapper:function(f){if(f.parent().is(".ui-effects-wrapper")){return f.parent()}var g={width:f.outerWidth(true),height:f.outerHeight(true),"float":f.css("float")};f.wrap('<div class="ui-effects-wrapper" style="font-size:100%;background:transparent;border:none;margin:0;padding:0"></div>');var j=f.parent();if(f.css("position")=="static"){j.css({position:"relative"});f.css({position:"relative"})}else{var i=f.css("top");if(isNaN(parseInt(i,10))){i="auto"}var h=f.css("left");if(isNaN(parseInt(h,10))){h="auto"}j.css({position:f.css("position"),top:i,left:h,zIndex:f.css("z-index")}).show();f.css({position:"relative",top:0,left:0})}j.css(g);return j},removeWrapper:function(f){if(f.parent().is(".ui-effects-wrapper")){return f.parent().replaceWith(f)}return f},setTransition:function(g,i,f,h){h=h||{};d.each(i,function(k,j){unit=g.cssUnit(j);if(unit[0]>0){h[j]=unit[0]*f+unit[1]}});return h},animateClass:function(h,i,k,j){var f=(typeof k=="function"?k:(j?j:null));var g=(typeof k=="string"?k:null);return this.each(function(){var q={};var o=d(this);var p=o.attr("style")||"";if(typeof p=="object"){p=p.cssText}if(h.toggle){o.hasClass(h.toggle)?h.remove=h.toggle:h.add=h.toggle}var l=d.extend({},(document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle));if(h.add){o.addClass(h.add)}if(h.remove){o.removeClass(h.remove)}var m=d.extend({},(document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle));if(h.add){o.removeClass(h.add)}if(h.remove){o.addClass(h.remove)}for(var r in m){if(typeof m[r]!="function"&&m[r]&&r.indexOf("Moz")==-1&&r.indexOf("length")==-1&&m[r]!=l[r]&&(r.match(/color/i)||(!r.match(/color/i)&&!isNaN(parseInt(m[r],10))))&&(l.position!="static"||(l.position=="static"&&!r.match(/left|top|bottom|right/)))){q[r]=m[r]}}o.animate(q,i,g,function(){if(typeof d(this).attr("style")=="object"){d(this).attr("style")["cssText"]="";d(this).attr("style")["cssText"]=p}else{d(this).attr("style",p)}if(h.add){d(this).addClass(h.add)}if(h.remove){d(this).removeClass(h.remove)}if(f){f.apply(this,arguments)}})})}};function c(g,f){var i=g[1]&&g[1].constructor==Object?g[1]:{};if(f){i.mode=f}var h=g[1]&&g[1].constructor!=Object?g[1]:(i.duration?i.duration:g[2]);h=d.fx.off?0:typeof h==="number"?h:d.fx.speeds[h]||d.fx.speeds._default;var j=i.callback||(d.isFunction(g[1])&&g[1])||(d.isFunction(g[2])&&g[2])||(d.isFunction(g[3])&&g[3]);return[g[0],i,h,j]}d.fn.extend({_show:d.fn.show,_hide:d.fn.hide,__toggle:d.fn.toggle,_addClass:d.fn.addClass,_removeClass:d.fn.removeClass,_toggleClass:d.fn.toggleClass,effect:function(g,f,h,i){return d.effects[g]?d.effects[g].call(this,{method:g,options:f||{},duration:h,callback:i}):null},show:function(){if(!arguments[0]||(arguments[0].constructor==Number||(/(slow|normal|fast)/).test(arguments[0]))){return this._show.apply(this,arguments)}else{return this.effect.apply(this,c(arguments,"show"))}},hide:function(){if(!arguments[0]||(arguments[0].constructor==Number||(/(slow|normal|fast)/).test(arguments[0]))){return this._hide.apply(this,arguments)}else{return this.effect.apply(this,c(arguments,"hide"))}},toggle:function(){if(!arguments[0]||(arguments[0].constructor==Number||(/(slow|normal|fast)/).test(arguments[0]))||(d.isFunction(arguments[0])||typeof arguments[0]=="boolean")){return this.__toggle.apply(this,arguments)}else{return this.effect.apply(this,c(arguments,"toggle"))}},addClass:function(g,f,i,h){return f?d.effects.animateClass.apply(this,[{add:g},f,i,h]):this._addClass(g)},removeClass:function(g,f,i,h){return f?d.effects.animateClass.apply(this,[{remove:g},f,i,h]):this._removeClass(g)},toggleClass:function(g,f,i,h){return((typeof f!=="boolean")&&f)?d.effects.animateClass.apply(this,[{toggle:g},f,i,h]):this._toggleClass(g,f)},morph:function(f,h,g,j,i){return d.effects.animateClass.apply(this,[{add:h,remove:f},g,j,i])},switchClass:function(){return this.morph.apply(this,arguments)},cssUnit:function(f){var g=this.css(f),h=[];d.each(["em","px","%","pt"],function(j,k){if(g.indexOf(k)>0){h=[parseFloat(g),k]}});return h}});d.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(g,f){d.fx.step[f]=function(h){if(h.state==0){h.start=e(h.elem,f);h.end=b(h.end)}h.elem.style[f]="rgb("+[Math.max(Math.min(parseInt((h.pos*(h.end[0]-h.start[0]))+h.start[0],10),255),0),Math.max(Math.min(parseInt((h.pos*(h.end[1]-h.start[1]))+h.start[1],10),255),0),Math.max(Math.min(parseInt((h.pos*(h.end[2]-h.start[2]))+h.start[2],10),255),0)].join(",")+")"}});function b(g){var f;if(g&&g.constructor==Array&&g.length==3){return g}if(f=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(g)){return[parseInt(f[1],10),parseInt(f[2],10),parseInt(f[3],10)]}if(f=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(g)){return[parseFloat(f[1])*2.55,parseFloat(f[2])*2.55,parseFloat(f[3])*2.55]}if(f=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(g)){return[parseInt(f[1],16),parseInt(f[2],16),parseInt(f[3],16)]}if(f=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(g)){return[parseInt(f[1]+f[1],16),parseInt(f[2]+f[2],16),parseInt(f[3]+f[3],16)]}if(f=/rgba\(0, 0, 0, 0\)/.exec(g)){return a.transparent}return a[d.trim(g).toLowerCase()]}function e(h,f){var g;do{g=d.curCSS(h,f);if(g!=""&&g!="transparent"||d.nodeName(h,"body")){break}f="backgroundColor"}while(h=h.parentNode);return b(g)}var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]};d.easing.jswing=d.easing.swing;d.extend(d.easing,{def:"easeOutQuad",swing:function(g,h,f,j,i){return d.easing[d.easing.def](g,h,f,j,i)},easeInQuad:function(g,h,f,j,i){return j*(h/=i)*h+f},easeOutQuad:function(g,h,f,j,i){return -j*(h/=i)*(h-2)+f},easeInOutQuad:function(g,h,f,j,i){if((h/=i/2)<1){return j/2*h*h+f}return -j/2*((--h)*(h-2)-1)+f},easeInCubic:function(g,h,f,j,i){return j*(h/=i)*h*h+f},easeOutCubic:function(g,h,f,j,i){return j*((h=h/i-1)*h*h+1)+f},easeInOutCubic:function(g,h,f,j,i){if((h/=i/2)<1){return j/2*h*h*h+f}return j/2*((h-=2)*h*h+2)+f},easeInQuart:function(g,h,f,j,i){return j*(h/=i)*h*h*h+f},easeOutQuart:function(g,h,f,j,i){return -j*((h=h/i-1)*h*h*h-1)+f},easeInOutQuart:function(g,h,f,j,i){if((h/=i/2)<1){return j/2*h*h*h*h+f}return -j/2*((h-=2)*h*h*h-2)+f},easeInQuint:function(g,h,f,j,i){return j*(h/=i)*h*h*h*h+f},easeOutQuint:function(g,h,f,j,i){return j*((h=h/i-1)*h*h*h*h+1)+f},easeInOutQuint:function(g,h,f,j,i){if((h/=i/2)<1){return j/2*h*h*h*h*h+f}return j/2*((h-=2)*h*h*h*h+2)+f},easeInSine:function(g,h,f,j,i){return -j*Math.cos(h/i*(Math.PI/2))+j+f},easeOutSine:function(g,h,f,j,i){return j*Math.sin(h/i*(Math.PI/2))+f},easeInOutSine:function(g,h,f,j,i){return -j/2*(Math.cos(Math.PI*h/i)-1)+f},easeInExpo:function(g,h,f,j,i){return(h==0)?f:j*Math.pow(2,10*(h/i-1))+f},easeOutExpo:function(g,h,f,j,i){return(h==i)?f+j:j*(-Math.pow(2,-10*h/i)+1)+f},easeInOutExpo:function(g,h,f,j,i){if(h==0){return f}if(h==i){return f+j}if((h/=i/2)<1){return j/2*Math.pow(2,10*(h-1))+f}return j/2*(-Math.pow(2,-10*--h)+2)+f},easeInCirc:function(g,h,f,j,i){return -j*(Math.sqrt(1-(h/=i)*h)-1)+f},easeOutCirc:function(g,h,f,j,i){return j*Math.sqrt(1-(h=h/i-1)*h)+f},easeInOutCirc:function(g,h,f,j,i){if((h/=i/2)<1){return -j/2*(Math.sqrt(1-h*h)-1)+f}return j/2*(Math.sqrt(1-(h-=2)*h)+1)+f},easeInElastic:function(g,i,f,m,l){var j=1.70158;var k=0;var h=m;if(i==0){return f}if((i/=l)==1){return f+m}if(!k){k=l*0.3}if(h<Math.abs(m)){h=m;var j=k/4}else{var j=k/(2*Math.PI)*Math.asin(m/h)}return -(h*Math.pow(2,10*(i-=1))*Math.sin((i*l-j)*(2*Math.PI)/k))+f},easeOutElastic:function(g,i,f,m,l){var j=1.70158;var k=0;var h=m;if(i==0){return f}if((i/=l)==1){return f+m}if(!k){k=l*0.3}if(h<Math.abs(m)){h=m;var j=k/4}else{var j=k/(2*Math.PI)*Math.asin(m/h)}return h*Math.pow(2,-10*i)*Math.sin((i*l-j)*(2*Math.PI)/k)+m+f},easeInOutElastic:function(g,i,f,m,l){var j=1.70158;var k=0;var h=m;if(i==0){return f}if((i/=l/2)==2){return f+m}if(!k){k=l*(0.3*1.5)}if(h<Math.abs(m)){h=m;var j=k/4}else{var j=k/(2*Math.PI)*Math.asin(m/h)}if(i<1){return -0.5*(h*Math.pow(2,10*(i-=1))*Math.sin((i*l-j)*(2*Math.PI)/k))+f}return h*Math.pow(2,-10*(i-=1))*Math.sin((i*l-j)*(2*Math.PI)/k)*0.5+m+f},easeInBack:function(g,h,f,k,j,i){if(i==undefined){i=1.70158}return k*(h/=j)*h*((i+1)*h-i)+f},easeOutBack:function(g,h,f,k,j,i){if(i==undefined){i=1.70158}return k*((h=h/j-1)*h*((i+1)*h+i)+1)+f},easeInOutBack:function(g,h,f,k,j,i){if(i==undefined){i=1.70158}if((h/=j/2)<1){return k/2*(h*h*(((i*=(1.525))+1)*h-i))+f}return k/2*((h-=2)*h*(((i*=(1.525))+1)*h+i)+2)+f},easeInBounce:function(g,h,f,j,i){return j-d.easing.easeOutBounce(g,i-h,0,j,i)+f},easeOutBounce:function(g,h,f,j,i){if((h/=i)<(1/2.75)){return j*(7.5625*h*h)+f}else{if(h<(2/2.75)){return j*(7.5625*(h-=(1.5/2.75))*h+0.75)+f}else{if(h<(2.5/2.75)){return j*(7.5625*(h-=(2.25/2.75))*h+0.9375)+f}else{return j*(7.5625*(h-=(2.625/2.75))*h+0.984375)+f}}}},easeInOutBounce:function(g,h,f,j,i){if(h<i/2){return d.easing.easeInBounce(g,h*2,0,j,i)*0.5+f}return d.easing.easeOutBounce(g,h*2-i,0,j,i)*0.5+j*0.5+f}})})(jQuery);;/*
 * jQuery UI Effects Blind 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Blind
 *
 * Depends:
 *	effects.core.js
 */
(function(a){a.effects.blind=function(b){return this.queue(function(){var d=a(this),c=["position","top","left"];var h=a.effects.setMode(d,b.options.mode||"hide");var g=b.options.direction||"vertical";a.effects.save(d,c);d.show();var j=a.effects.createWrapper(d).css({overflow:"hidden"});var e=(g=="vertical")?"height":"width";var i=(g=="vertical")?j.height():j.width();if(h=="show"){j.css(e,0)}var f={};f[e]=h=="show"?i:0;j.animate(f,b.duration,b.options.easing,function(){if(h=="hide"){d.hide()}a.effects.restore(d,c);a.effects.removeWrapper(d);if(b.callback){b.callback.apply(d[0],arguments)}d.dequeue()})})}})(jQuery);;/*
 * jQuery UI Effects Bounce 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Bounce
 *
 * Depends:
 *	effects.core.js
 */
(function(a){a.effects.bounce=function(b){return this.queue(function(){var e=a(this),l=["position","top","left"];var k=a.effects.setMode(e,b.options.mode||"effect");var n=b.options.direction||"up";var c=b.options.distance||20;var d=b.options.times||5;var g=b.duration||250;if(/show|hide/.test(k)){l.push("opacity")}a.effects.save(e,l);e.show();a.effects.createWrapper(e);var f=(n=="up"||n=="down")?"top":"left";var p=(n=="up"||n=="left")?"pos":"neg";var c=b.options.distance||(f=="top"?e.outerHeight({margin:true})/3:e.outerWidth({margin:true})/3);if(k=="show"){e.css("opacity",0).css(f,p=="pos"?-c:c)}if(k=="hide"){c=c/(d*2)}if(k!="hide"){d--}if(k=="show"){var h={opacity:1};h[f]=(p=="pos"?"+=":"-=")+c;e.animate(h,g/2,b.options.easing);c=c/2;d--}for(var j=0;j<d;j++){var o={},m={};o[f]=(p=="pos"?"-=":"+=")+c;m[f]=(p=="pos"?"+=":"-=")+c;e.animate(o,g/2,b.options.easing).animate(m,g/2,b.options.easing);c=(k=="hide")?c*2:c/2}if(k=="hide"){var h={opacity:0};h[f]=(p=="pos"?"-=":"+=")+c;e.animate(h,g/2,b.options.easing,function(){e.hide();a.effects.restore(e,l);a.effects.removeWrapper(e);if(b.callback){b.callback.apply(this,arguments)}})}else{var o={},m={};o[f]=(p=="pos"?"-=":"+=")+c;m[f]=(p=="pos"?"+=":"-=")+c;e.animate(o,g/2,b.options.easing).animate(m,g/2,b.options.easing,function(){a.effects.restore(e,l);a.effects.removeWrapper(e);if(b.callback){b.callback.apply(this,arguments)}})}e.queue("fx",function(){e.dequeue()});e.dequeue()})}})(jQuery);;/*
 * jQuery UI Effects Clip 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Clip
 *
 * Depends:
 *	effects.core.js
 */
(function(a){a.effects.clip=function(b){return this.queue(function(){var f=a(this),j=["position","top","left","height","width"];var i=a.effects.setMode(f,b.options.mode||"hide");var k=b.options.direction||"vertical";a.effects.save(f,j);f.show();var c=a.effects.createWrapper(f).css({overflow:"hidden"});var e=f[0].tagName=="IMG"?c:f;var g={size:(k=="vertical")?"height":"width",position:(k=="vertical")?"top":"left"};var d=(k=="vertical")?e.height():e.width();if(i=="show"){e.css(g.size,0);e.css(g.position,d/2)}var h={};h[g.size]=i=="show"?d:0;h[g.position]=i=="show"?0:d/2;e.animate(h,{queue:false,duration:b.duration,easing:b.options.easing,complete:function(){if(i=="hide"){f.hide()}a.effects.restore(f,j);a.effects.removeWrapper(f);if(b.callback){b.callback.apply(f[0],arguments)}f.dequeue()}})})}})(jQuery);;/*
 * jQuery UI Effects Drop 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Drop
 *
 * Depends:
 *	effects.core.js
 */
(function(a){a.effects.drop=function(b){return this.queue(function(){var e=a(this),d=["position","top","left","opacity"];var i=a.effects.setMode(e,b.options.mode||"hide");var h=b.options.direction||"left";a.effects.save(e,d);e.show();a.effects.createWrapper(e);var f=(h=="up"||h=="down")?"top":"left";var c=(h=="up"||h=="left")?"pos":"neg";var j=b.options.distance||(f=="top"?e.outerHeight({margin:true})/2:e.outerWidth({margin:true})/2);if(i=="show"){e.css("opacity",0).css(f,c=="pos"?-j:j)}var g={opacity:i=="show"?1:0};g[f]=(i=="show"?(c=="pos"?"+=":"-="):(c=="pos"?"-=":"+="))+j;e.animate(g,{queue:false,duration:b.duration,easing:b.options.easing,complete:function(){if(i=="hide"){e.hide()}a.effects.restore(e,d);a.effects.removeWrapper(e);if(b.callback){b.callback.apply(this,arguments)}e.dequeue()}})})}})(jQuery);;/*
 * jQuery UI Effects Explode 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Explode
 *
 * Depends:
 *	effects.core.js
 */
(function(a){a.effects.explode=function(b){return this.queue(function(){var k=b.options.pieces?Math.round(Math.sqrt(b.options.pieces)):3;var e=b.options.pieces?Math.round(Math.sqrt(b.options.pieces)):3;b.options.mode=b.options.mode=="toggle"?(a(this).is(":visible")?"hide":"show"):b.options.mode;var h=a(this).show().css("visibility","hidden");var l=h.offset();l.top-=parseInt(h.css("marginTop"),10)||0;l.left-=parseInt(h.css("marginLeft"),10)||0;var g=h.outerWidth(true);var c=h.outerHeight(true);for(var f=0;f<k;f++){for(var d=0;d<e;d++){h.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-d*(g/e),top:-f*(c/k)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:g/e,height:c/k,left:l.left+d*(g/e)+(b.options.mode=="show"?(d-Math.floor(e/2))*(g/e):0),top:l.top+f*(c/k)+(b.options.mode=="show"?(f-Math.floor(k/2))*(c/k):0),opacity:b.options.mode=="show"?0:1}).animate({left:l.left+d*(g/e)+(b.options.mode=="show"?0:(d-Math.floor(e/2))*(g/e)),top:l.top+f*(c/k)+(b.options.mode=="show"?0:(f-Math.floor(k/2))*(c/k)),opacity:b.options.mode=="show"?1:0},b.duration||500)}}setTimeout(function(){b.options.mode=="show"?h.css({visibility:"visible"}):h.css({visibility:"visible"}).hide();if(b.callback){b.callback.apply(h[0])}h.dequeue();a("div.ui-effects-explode").remove()},b.duration||500)})}})(jQuery);;/*
 * jQuery UI Effects Fold 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Fold
 *
 * Depends:
 *	effects.core.js
 */
(function(a){a.effects.fold=function(b){return this.queue(function(){var e=a(this),k=["position","top","left"];var h=a.effects.setMode(e,b.options.mode||"hide");var o=b.options.size||15;var n=!(!b.options.horizFirst);var g=b.duration?b.duration/2:a.fx.speeds._default/2;a.effects.save(e,k);e.show();var d=a.effects.createWrapper(e).css({overflow:"hidden"});var i=((h=="show")!=n);var f=i?["width","height"]:["height","width"];var c=i?[d.width(),d.height()]:[d.height(),d.width()];var j=/([0-9]+)%/.exec(o);if(j){o=parseInt(j[1],10)/100*c[h=="hide"?0:1]}if(h=="show"){d.css(n?{height:0,width:o}:{height:o,width:0})}var m={},l={};m[f[0]]=h=="show"?c[0]:o;l[f[1]]=h=="show"?c[1]:0;d.animate(m,g,b.options.easing).animate(l,g,b.options.easing,function(){if(h=="hide"){e.hide()}a.effects.restore(e,k);a.effects.removeWrapper(e);if(b.callback){b.callback.apply(e[0],arguments)}e.dequeue()})})}})(jQuery);;/*
 * jQuery UI Effects Highlight 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Highlight
 *
 * Depends:
 *	effects.core.js
 */
(function(a){a.effects.highlight=function(b){return this.queue(function(){var e=a(this),d=["backgroundImage","backgroundColor","opacity"];var h=a.effects.setMode(e,b.options.mode||"show");var c=b.options.color||"#ffff99";var g=e.css("backgroundColor");a.effects.save(e,d);e.show();e.css({backgroundImage:"none",backgroundColor:c});var f={backgroundColor:g};if(h=="hide"){f.opacity=0}e.animate(f,{queue:false,duration:b.duration,easing:b.options.easing,complete:function(){if(h=="hide"){e.hide()}a.effects.restore(e,d);if(h=="show"&&a.browser.msie){this.style.removeAttribute("filter")}if(b.callback){b.callback.apply(this,arguments)}e.dequeue()}})})}})(jQuery);;/*
 * jQuery UI Effects Pulsate 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Pulsate
 *
 * Depends:
 *	effects.core.js
 */
(function(a){a.effects.pulsate=function(b){return this.queue(function(){var d=a(this);var g=a.effects.setMode(d,b.options.mode||"show");var f=b.options.times||5;var e=b.duration?b.duration/2:a.fx.speeds._default/2;if(g=="hide"){f--}if(d.is(":hidden")){d.css("opacity",0);d.show();d.animate({opacity:1},e,b.options.easing);f=f-2}for(var c=0;c<f;c++){d.animate({opacity:0},e,b.options.easing).animate({opacity:1},e,b.options.easing)}if(g=="hide"){d.animate({opacity:0},e,b.options.easing,function(){d.hide();if(b.callback){b.callback.apply(this,arguments)}})}else{d.animate({opacity:0},e,b.options.easing).animate({opacity:1},e,b.options.easing,function(){if(b.callback){b.callback.apply(this,arguments)}})}d.queue("fx",function(){d.dequeue()});d.dequeue()})}})(jQuery);;/*
 * jQuery UI Effects Scale 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Scale
 *
 * Depends:
 *	effects.core.js
 */
(function(a){a.effects.puff=function(b){return this.queue(function(){var f=a(this);var c=a.extend(true,{},b.options);var h=a.effects.setMode(f,b.options.mode||"hide");var g=parseInt(b.options.percent,10)||150;c.fade=true;var e={height:f.height(),width:f.width()};var d=g/100;f.from=(h=="hide")?e:{height:e.height*d,width:e.width*d};c.from=f.from;c.percent=(h=="hide")?g:100;c.mode=h;f.effect("scale",c,b.duration,b.callback);f.dequeue()})};a.effects.scale=function(b){return this.queue(function(){var g=a(this);var d=a.extend(true,{},b.options);var j=a.effects.setMode(g,b.options.mode||"effect");var h=parseInt(b.options.percent,10)||(parseInt(b.options.percent,10)==0?0:(j=="hide"?0:100));var i=b.options.direction||"both";var c=b.options.origin;if(j!="effect"){d.origin=c||["middle","center"];d.restore=true}var f={height:g.height(),width:g.width()};g.from=b.options.from||(j=="show"?{height:0,width:0}:f);var e={y:i!="horizontal"?(h/100):1,x:i!="vertical"?(h/100):1};g.to={height:f.height*e.y,width:f.width*e.x};if(b.options.fade){if(j=="show"){g.from.opacity=0;g.to.opacity=1}if(j=="hide"){g.from.opacity=1;g.to.opacity=0}}d.from=g.from;d.to=g.to;d.mode=j;g.effect("size",d,b.duration,b.callback);g.dequeue()})};a.effects.size=function(b){return this.queue(function(){var c=a(this),n=["position","top","left","width","height","overflow","opacity"];var m=["position","top","left","overflow","opacity"];var j=["width","height","overflow"];var p=["fontSize"];var k=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"];var f=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"];var g=a.effects.setMode(c,b.options.mode||"effect");var i=b.options.restore||false;var e=b.options.scale||"both";var o=b.options.origin;var d={height:c.height(),width:c.width()};c.from=b.options.from||d;c.to=b.options.to||d;if(o){var h=a.effects.getBaseline(o,d);c.from.top=(d.height-c.from.height)*h.y;c.from.left=(d.width-c.from.width)*h.x;c.to.top=(d.height-c.to.height)*h.y;c.to.left=(d.width-c.to.width)*h.x}var l={from:{y:c.from.height/d.height,x:c.from.width/d.width},to:{y:c.to.height/d.height,x:c.to.width/d.width}};if(e=="box"||e=="both"){if(l.from.y!=l.to.y){n=n.concat(k);c.from=a.effects.setTransition(c,k,l.from.y,c.from);c.to=a.effects.setTransition(c,k,l.to.y,c.to)}if(l.from.x!=l.to.x){n=n.concat(f);c.from=a.effects.setTransition(c,f,l.from.x,c.from);c.to=a.effects.setTransition(c,f,l.to.x,c.to)}}if(e=="content"||e=="both"){if(l.from.y!=l.to.y){n=n.concat(p);c.from=a.effects.setTransition(c,p,l.from.y,c.from);c.to=a.effects.setTransition(c,p,l.to.y,c.to)}}a.effects.save(c,i?n:m);c.show();a.effects.createWrapper(c);c.css("overflow","hidden").css(c.from);if(e=="content"||e=="both"){k=k.concat(["marginTop","marginBottom"]).concat(p);f=f.concat(["marginLeft","marginRight"]);j=n.concat(k).concat(f);c.find("*[width]").each(function(){child=a(this);if(i){a.effects.save(child,j)}var q={height:child.height(),width:child.width()};child.from={height:q.height*l.from.y,width:q.width*l.from.x};child.to={height:q.height*l.to.y,width:q.width*l.to.x};if(l.from.y!=l.to.y){child.from=a.effects.setTransition(child,k,l.from.y,child.from);child.to=a.effects.setTransition(child,k,l.to.y,child.to)}if(l.from.x!=l.to.x){child.from=a.effects.setTransition(child,f,l.from.x,child.from);child.to=a.effects.setTransition(child,f,l.to.x,child.to)}child.css(child.from);child.animate(child.to,b.duration,b.options.easing,function(){if(i){a.effects.restore(child,j)}})})}c.animate(c.to,{queue:false,duration:b.duration,easing:b.options.easing,complete:function(){if(g=="hide"){c.hide()}a.effects.restore(c,i?n:m);a.effects.removeWrapper(c);if(b.callback){b.callback.apply(this,arguments)}c.dequeue()}})})}})(jQuery);;/*
 * jQuery UI Effects Shake 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Shake
 *
 * Depends:
 *	effects.core.js
 */
(function(a){a.effects.shake=function(b){return this.queue(function(){var e=a(this),l=["position","top","left"];var k=a.effects.setMode(e,b.options.mode||"effect");var n=b.options.direction||"left";var c=b.options.distance||20;var d=b.options.times||3;var g=b.duration||b.options.duration||140;a.effects.save(e,l);e.show();a.effects.createWrapper(e);var f=(n=="up"||n=="down")?"top":"left";var p=(n=="up"||n=="left")?"pos":"neg";var h={},o={},m={};h[f]=(p=="pos"?"-=":"+=")+c;o[f]=(p=="pos"?"+=":"-=")+c*2;m[f]=(p=="pos"?"-=":"+=")+c*2;e.animate(h,g,b.options.easing);for(var j=1;j<d;j++){e.animate(o,g,b.options.easing).animate(m,g,b.options.easing)}e.animate(o,g,b.options.easing).animate(h,g/2,b.options.easing,function(){a.effects.restore(e,l);a.effects.removeWrapper(e);if(b.callback){b.callback.apply(this,arguments)}});e.queue("fx",function(){e.dequeue()});e.dequeue()})}})(jQuery);;/*
 * jQuery UI Effects Slide 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Slide
 *
 * Depends:
 *	effects.core.js
 */
(function(a){a.effects.slide=function(b){return this.queue(function(){var e=a(this),d=["position","top","left"];var i=a.effects.setMode(e,b.options.mode||"show");var h=b.options.direction||"left";a.effects.save(e,d);e.show();a.effects.createWrapper(e).css({overflow:"hidden"});var f=(h=="up"||h=="down")?"top":"left";var c=(h=="up"||h=="left")?"pos":"neg";var j=b.options.distance||(f=="top"?e.outerHeight({margin:true}):e.outerWidth({margin:true}));if(i=="show"){e.css(f,c=="pos"?-j:j)}var g={};g[f]=(i=="show"?(c=="pos"?"+=":"-="):(c=="pos"?"-=":"+="))+j;e.animate(g,{queue:false,duration:b.duration,easing:b.options.easing,complete:function(){if(i=="hide"){e.hide()}a.effects.restore(e,d);a.effects.removeWrapper(e);if(b.callback){b.callback.apply(this,arguments)}e.dequeue()}})})}})(jQuery);;/*
 * jQuery UI Effects Transfer 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Transfer
 *
 * Depends:
 *	effects.core.js
 */
(function(a){a.effects.transfer=function(b){return this.queue(function(){var f=a(this),h=a(b.options.to),e=h.offset(),g={top:e.top,left:e.left,height:h.innerHeight(),width:h.innerWidth()},d=f.offset(),c=a('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(b.options.className).css({top:d.top,left:d.left,height:f.innerHeight(),width:f.innerWidth(),position:"absolute"}).animate(g,b.duration,b.options.easing,function(){c.remove();(b.callback&&b.callback.apply(f[0],arguments));f.dequeue()})})}})(jQuery);;
 /*
 * jQuery UI selectmenu
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 *
 * http://jquery-ui.googlecode.com/svn/branches/labs/selectmenu/ui.selectmenu.js
 */

(function($) {

$.widget("ui.selectmenu", {
	_init: function() {
		var self = this, o = this.options;

		//quick array of button and menu id's
		var num = Math.round(Math.random() * 1000);
		this.ids = [this.element.attr('id') + '_' + 'button' + '_' + num, this.element.attr('id') + '_' + 'menu' + '_' + num];

		//define safe mouseup for future toggling
		this._safemouseup = true;

		//create menu button wrapper
		this.newelement = $('<a class="'+ this.widgetBaseClass +' ui-widget ui-state-default ui-corner-all" id="'+this.ids[0]+'" role="button" href="#" aria-haspopup="true" aria-owns="'+this.ids[1]+'" aria-expanded="false"></a>')
			.insertAfter(this.element);

		//transfer tabindex
		var tabindex = this.element.attr('tabindex') || '0';
		this.newelement.attr('tabindex', tabindex);

		//save reference to select in data for ease in calling methods
		this.newelement.data('selectelement', this.element);

		//menu icon
		this.selectmenuIcon = $('<span class="'+ this.widgetBaseClass +'-icon ui-icon"></span>')
			.prependTo(this.newelement)
			.addClass( (o.style == "popup")? 'ui-icon-triangle-2-n-s' : 'ui-icon-triangle-1-s' );


		//make associated form label trigger focus
		$('label[for='+this.element.attr('id')+']')
			.attr('for', this.ids[0])
			.bind('click', function(){
				self.newelement.focus();
				return false;
			});

		//click toggle for menu visibility
		this.newelement
			.bind('mousedown', function(event){
				self._toggle(event);
				//make sure a click won't open/close instantly
				if(o.style == "popup"){
					self._safemouseup = false;
					setTimeout(function(){self._safemouseup = true;}, 300);
				}
				return false;
			})
			.bind('click',function(){
				return false;
			})
			.keydown(function(event){
				var ret = true;
				switch (event.keyCode) {
					case $.ui.keyCode.ENTER:
						ret = true;
						break;
					case $.ui.keyCode.SPACE:
						ret = false;
						self._toggle(event);
						break;
					case $.ui.keyCode.UP:
					case $.ui.keyCode.LEFT:
						ret = false;
						self._moveSelection(-1);
						break;
					case $.ui.keyCode.DOWN:
					case $.ui.keyCode.RIGHT:
						ret = false;
						self._moveSelection(1);
						break;
					case $.ui.keyCode.TAB:
						ret = true;
						break;
					default:
						ret = false;
						self._typeAhead(event.keyCode, 'mouseup');
						break;
				}
				return ret;
			})
			.bind('mouseover focus', function(){
				$(this).addClass(self.widgetBaseClass+'-focus ui-state-hover');
			})
			.bind('mouseout blur', function(){
				$(this).removeClass(self.widgetBaseClass+'-focus ui-state-hover');
			});

		//document click closes menu
		$(document)
			.mousedown(function(event){
				self.close(event);
			});

		//change event on original selectmenu
		this.element
			.click(function(){ this._refreshValue(); })
			.focus(function(){ this.newelement.focus(); });

		//create menu portion, append to body
		var cornerClass = (o.style == "dropdown")? " ui-corner-bottom" : " ui-corner-all"
		this.list = $('<ul class="' + self.widgetBaseClass + '-menu ui-widget ui-widget-content'+cornerClass+'" aria-hidden="true" role="listbox" aria-multiselectable="false" aria-labelledby="'+this.ids[0]+'" id="'+this.ids[1]+'"></ul>').appendTo('body');

		//serialize selectmenu element options
		var selectOptionData = [];
		this.element
			.find('option')
			.each(function(){
				selectOptionData.push({
					value: $(this).attr('value'),
					text: self._formatText(jQuery(this).text()),
					selected: $(this).attr('selected'),
					classes: $(this).attr('class'),
					parentOptGroup: $(this).parent('optgroup').attr('label')
				});
			});

		//active state class is only used in popup style
		var activeClass = (self.options.style == "popup") ? " ui-state-active" : "";

		//write li's
		for(var i in selectOptionData){
			var thisLi = $('<li><a href="#" tabindex="-1" role="option" aria-selected="false">'+ selectOptionData[i].text +'</a></li>')
				.data('index',i)
				.addClass(selectOptionData[i].classes)
				.data('optionClasses', selectOptionData[i].classes)
				.mouseup(function(event){
						if(self._safemouseup){
							var changed = $(this).data('index') != self._selectedIndex();
							self.value($(this).data('index'));
							self.select(event);
							if(changed){ self.change(event); }
							self.close(event,true);
						}
					return false;
				})
				.click(function(){
					return false;
				})
				.bind('mouseover focus', function(){
					self._selectedOptionLi().addClass(activeClass);
					self._focusedOptionLi().removeClass(self.widgetBaseClass+'-item-focus ui-state-hover');
					$(this).removeClass('ui-state-active').addClass(self.widgetBaseClass + '-item-focus ui-state-hover');
				})
				.bind('mouseout blur', function(){
					if($(this).is( self._selectedOptionLi() )){ $(this).addClass(activeClass); }
					$(this).removeClass(self.widgetBaseClass + '-item-focus ui-state-hover');
				});

			//optgroup or not...
			if(selectOptionData[i].parentOptGroup){
				var optGroupName = self.widgetBaseClass + '-group-' + selectOptionData[i].parentOptGroup;
				if(this.list.find('li.' + optGroupName).size()){
					this.list.find('li.' + optGroupName + ':last ul').append(thisLi);
				}
				else{
					$('<li class="'+self.widgetBaseClass+'-group '+optGroupName+'"><span class="'+self.widgetBaseClass+'-group-label">'+selectOptionData[i].parentOptGroup+'</span><ul></ul></li>')
						.appendTo(this.list)
						.find('ul')
						.append(thisLi);
				}
			}
			else{
				thisLi.appendTo(this.list);
			}

			//this allows for using the scrollbar in an overflowed list
			this.list.bind('mousedown mouseup', function(){return false;});

			//append icon if option is specified
			if(o.icons){
				for(var j in o.icons){
					if(thisLi.is(o.icons[j].find)){
						thisLi
							.data('optionClasses', selectOptionData[i].classes + ' ' + self.widgetBaseClass + '-hasIcon')
							.addClass(self.widgetBaseClass + '-hasIcon');
						var iconClass = o.icons[j].icon || "";

						thisLi
							.find('a:eq(0)')
							.prepend('<span class="'+self.widgetBaseClass+'-item-icon ui-icon '+iconClass + '"></span>');
					}
				}
			}
		}

		//add corners to top and bottom menu items
		this.list.find('li:last').addClass("ui-corner-bottom");
		if(o.style == 'popup'){ this.list.find('li:first').addClass("ui-corner-top"); }

		//transfer classes to selectmenu and list
		if(o.transferClasses){
			var transferClasses = this.element.attr('class') || '';
			this.newelement.add(this.list).addClass(transferClasses);
		}

		//original selectmenu width
		var selectWidth = this.element.width();

		//set menu button width
		this.newelement.width( (o.width) ? o.width : selectWidth);

		//set menu width to either menuWidth option value, width option value, or select width
		if(o.style == 'dropdown'){ this.list.width( (o.menuWidth) ? o.menuWidth : ((o.width) ? o.width : selectWidth)); }
		else { this.list.width( (o.menuWidth) ? o.menuWidth : ((o.width) ? o.width - o.handleWidth : selectWidth - o.handleWidth)); }

		//set max height from option
		if(o.maxHeight && o.maxHeight < this.list.height()){ this.list.height(o.maxHeight); }

		//save reference to actionable li's (not group label li's)
		this._optionLis = this.list.find('li:not(.'+ self.widgetBaseClass +'-group)');

		//transfer menu click to menu button
		this.list
			.keydown(function(event){
				var ret = true;
				switch (event.keyCode) {
					case $.ui.keyCode.UP:
					case $.ui.keyCode.LEFT:
						ret = false;
						self._moveFocus(-1);
						break;
					case $.ui.keyCode.DOWN:
					case $.ui.keyCode.RIGHT:
						ret = false;
						self._moveFocus(1);
						break;
					case $.ui.keyCode.HOME:
						ret = false;
						self._moveFocus(':first');
						break;
					case $.ui.keyCode.PAGE_UP:
						ret = false;
						self._scrollPage('up');
						break;
					case $.ui.keyCode.PAGE_DOWN:
						ret = false;
						self._scrollPage('down');
						break;
					case $.ui.keyCode.END:
						ret = false;
						self._moveFocus(':last');
						break;
					case $.ui.keyCode.ENTER:
					case $.ui.keyCode.SPACE:
						ret = false;
						self.close(event,true);
						$(event.target).parents('li:eq(0)').trigger('mouseup');
						break;
					case $.ui.keyCode.TAB:
						ret = true;
						self.close(event);
						break;
					case $.ui.keyCode.ESCAPE:
						ret = false;
						self.close(event,true);
						break;
					default:
						ret = false;
						self._typeAhead(event.keyCode,'focus');
						break;
				}
				return ret;
			});

		//selectmenu style
		if(o.style == 'dropdown'){
			this.newelement
				.addClass(self.widgetBaseClass+"-dropdown");
			this.list
				.addClass(self.widgetBaseClass+"-menu-dropdown");
		}
		else {
			this.newelement
				.addClass(self.widgetBaseClass+"-popup");
			this.list
				.addClass(self.widgetBaseClass+"-menu-popup");
		}

		//append status span to button
		this.newelement.prepend('<span class="'+self.widgetBaseClass+'-status">'+ selectOptionData[this._selectedIndex()].text +'</span>');

		//hide original selectmenu element
		this.element.hide();

		//transfer disabled state
		if(this.element.attr('disabled') == true){ this.disable(); }

		//update value
		this.value(this._selectedIndex());
	},
	destroy: function() {
		this.element.removeData(this.widgetName)
			.removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
			.removeAttr('aria-disabled');

		//unbind click on label, reset its for attr
		$('label[for='+this.newelement.attr('id')+']')
			.attr('for',this.element.attr('id'))
			.unbind('click');
		this.newelement.remove();
		this.list.remove();
		this.element.show();
	},
	_typeAhead: function(code, eventType){
		var self = this;
		//define self._prevChar if needed
		if(!self._prevChar){ self._prevChar = ['',0]; }
		var C = String.fromCharCode(code);
		c = C.toLowerCase();
		var focusFound = false;
		function focusOpt(elem, ind){
			focusFound = true;
			$(elem).trigger(eventType);
			self._prevChar[1] = ind;
		};
		this.list.find('li a').each(function(i){
			if(!focusFound){
				var thisText = $(this).text();
				if( thisText.indexOf(C) == 0 || thisText.indexOf(c) == 0){
						if(self._prevChar[0] == C){
							if(self._prevChar[1] < i){ focusOpt(this,i); }
						}
						else{ focusOpt(this,i); }
				}
			}
		});
		this._prevChar[0] = C;
	},
	_uiHash: function(){
		return {
			value: this.value()
		};
	},
	open: function(event){
		var self = this;
		this._refreshPosition();
		this._closeOthers(event);
		this.newelement
			.attr('aria-expanded', true)
			.addClass('ui-state-active');

		this.list
			.appendTo('body')
			.addClass(self.widgetBaseClass + '-open')
			.attr('aria-hidden', false)
			.find('li:not(.'+ self.widgetBaseClass +'-group):eq('+ this._selectedIndex() +') a').focus();
		if(this.options.style == "dropdown"){ this.newelement.removeClass('ui-corner-all').addClass('ui-corner-top'); }
		this._refreshPosition();
		this._trigger("open", event, this._uiHash());
	},
	close: function(event, retainFocus){
		if(this.newelement.is('.ui-state-active')){
			this.newelement
				.attr('aria-expanded', false)
				.removeClass('ui-state-active');
			this.list
				.attr('aria-hidden', true)
				.removeClass(this.widgetBaseClass+'-open');
			if(this.options.style == "dropdown"){ this.newelement.removeClass('ui-corner-top').addClass('ui-corner-all'); }
			if(retainFocus){this.newelement.focus();}
			this._trigger("close", event, this._uiHash());
		}
	},
	change: function(event) {
		this.element.trigger('change');
		this._trigger("change", event, this._uiHash());
	},
	select: function(event) {
		this._trigger("select", event, this._uiHash());
	},
	_closeOthers: function(event){
		$('.'+ this.widgetBaseClass +'.ui-state-active').not(this.newelement).each(function(){
			$(this).data('selectelement').selectmenu('close',event);
		});
		$('.'+ this.widgetBaseClass +'.ui-state-hover').trigger('mouseout');
	},
	_toggle: function(event,retainFocus){
		if(this.list.is('.'+ this.widgetBaseClass +'-open')){ this.close(event,retainFocus); }
		else { this.open(event); }
	},
	_formatText: function(text){
		return this.options.format ? this.options.format(text) : text;
	},
	_selectedIndex: function(){
		return this.element[0].selectedIndex;
	},
	_selectedOptionLi: function(){
		return this._optionLis.eq(this._selectedIndex());
	},
	_focusedOptionLi: function(){
		return this.list.find('.'+ this.widgetBaseClass +'-item-focus');
	},
	_moveSelection: function(amt){
		var currIndex = parseInt(this._selectedOptionLi().data('index'), 10);
		var newIndex = currIndex + amt;
		return this._optionLis.eq(newIndex).trigger('mouseup');
	},
	_moveFocus: function(amt){
		if(!isNaN(amt)){
			var currIndex = parseInt(this._focusedOptionLi().data('index'), 10);
			var newIndex = currIndex + amt;
		}
		else { var newIndex = parseInt(this._optionLis.filter(amt).data('index'), 10); }

		if(newIndex < 0){ newIndex = 0; }
		if(newIndex > this._optionLis.size()-1){
			newIndex =  this._optionLis.size()-1;
		}
		this._focusedOptionLi().find('a:eq(0)').blur();
		this._optionLis.eq(newIndex).find('a:eq(0)').focus();
	},
	_scrollPage: function(direction){
		var numPerPage = Math.floor(this.list.outerHeight() / this.list.find('li:first').outerHeight());
		numPerPage = (direction == 'up') ? -numPerPage : numPerPage;
		this._moveFocus(numPerPage);
	},
	_setData: function(key, value) {
		this.options[key] = value;
		if (key == 'disabled') {
			this.element
				.add(this.newelement)
				.add(this.list)
					[value ? 'addClass' : 'removeClass'](
						this.widgetBaseClass + '-disabled' + ' ' +
						this.namespace + '-state-disabled')
					.attr("aria-disabled", value);
		}
	},
	value: function(newValue) {
		if (arguments.length) {
			this.element[0].selectedIndex = newValue;
			this._refreshValue();
			this._refreshPosition();
		}
		return this.element[0].selectedIndex;
	},
	_refreshValue: function() {
		var activeClass = (this.options.style == "popup") ? " ui-state-active" : "";
		//deselect previous
		this.list
			.find('.'+ this.widgetBaseClass +'-item-selected')
			.removeClass(this.widgetBaseClass + "-item-selected" + activeClass)
			.find('a')
			.attr('aria-selected', 'false');
		//select new
		this._selectedOptionLi()
			.addClass(this.widgetBaseClass + "-item-selected"+activeClass)
			.find('a')
			.attr('aria-selected', 'true');
		//toggle any class brought in from option
		var currentOptionClasses = this.newelement.data('optionClasses') ? this.newelement.data('optionClasses') : "";
		var newOptionClasses = this._selectedOptionLi().data('optionClasses') ? this._selectedOptionLi().data('optionClasses') : "";
		this.newelement
			.removeClass(currentOptionClasses)
			.data('optionClasses', newOptionClasses)
			.addClass( newOptionClasses )
			.find('.'+this.widgetBaseClass+'-status')
			.html(
				this._selectedOptionLi()
					.find('a:eq(0)')
					.html()
			);
	},
	_refreshPosition: function(){
		//set left value
		this.list.css('left', this.newelement.offset().left);

		//set top value
		var menuTop = this.newelement.offset().top;
		var scrolledAmt = this.list[0].scrollTop;
		this.list.find('li:lt('+this._selectedIndex()+')').each(function(){
			scrolledAmt -= $(this).outerHeight();
		});

		if(this.newelement.is('.'+this.widgetBaseClass+'-popup')){
			menuTop+=scrolledAmt;
			this.list.css('top', menuTop);
		}
		else {
			menuTop += this.newelement.height();
			this.list.css('top', menuTop);
		}
	}
});

$.extend($.ui.selectmenu, {
	getter: "value",
	version: "@VERSION",
	eventPrefix: "selectmenu",
	defaults: {
		transferClasses: true,
		style: 'popup',
		width: null,
		menuWidth: null,
		handleWidth: 26,
		maxHeight: null,
		icons: null,
		format: null
	}
});

})(jQuery);
/**
 * Utility jQuery Plugins
 *   Most of these are small utility functions/suites, and being so small, we copy the uncompressed source in
 *   The exception to this is the url parser function, which might be big enough to belong with the widgets.
 *
 * TOC:
 *   (General Programming)
 *     iff
 *     others      - inverts current selection, can also be used as an else for iff
 *     tap         - insert an arbitrary function into a jquery chain
 *     once        - execute an arbitrary function only one time (globally)
 *     type        - guesstimates datatype, jquery 1.8 should have this functionality builtin
 *     timers:     - wrapper for setTimeout, setInterval, etc
 *       everyTime
 *       oneTime
 *       stopTime
 *     uniq
 *     url parser
 *     postMessage
 *
 *   (Attributes)
 *     id
 *     batch:
 *       attrs, styles, offsets, widths, heights, htmls, texts, val, ids
 *     metadata
 *     caret       - gets or sets input caret within a text input or textarea
 *
 *   (Selectors)
 *     getUniqueSelector
 *     :startOfLine
 *     :endOfLine
 *     Viewport Selectors
 *     Bound Events
 *
 *   (DOM)
 *     unwrap
 */

/**
 *  Workaround for broken $.fn.switchClass
 *  official version of this function uses the morphing function, and breaks in IE8
 */
(function($) {
  $.fn.switchClass = function(oldClass, newClass) {
    return this.removeClass(oldClass).addClass(newClass);
  };
})(jQuery);

/**
 * iff - v0.2 - 6/3/2009
 * http://benalman.com/projects/jquery-iff-plugin/
 *
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Licensed under the MIT license
 * http://benalman.com/about/license/
 */
(function($){
  '$:nomunge'; // Used by YUI compressor.

  $.fn.iff = function( test ) {
    var elems = !test || $.isFunction( test )
      && !test.apply( this, Array.prototype.slice.call(arguments, 1) )
      ? []
      : this;
    return this.pushStack( elems, 'iff', test );
  };

})(jQuery);

/**
 * Others
 */
jQuery.fn.others=function(){
	return this.end().not(this);
};

/**
 * ©2009 Jiayong Ou
 *
 * License (MIT):
 * http://github.com/jou/jquery.tap.js/blob/master/LICENSE
 */
(function(){
  jQuery.fn.tap = function(fn /* [callback_arg], [callback_arg], [...] */) {
    var args = jQuery.makeArray(arguments);
    args.unshift();

    fn.apply(this, args);
    return this;
  };
}());

/**
 * Filters elements that have not yet been processed.
 *
 * @param id
 *   If this is a string, it will be used in the class name applied to
 *   the elements for determining whether it has already been processed.
 *   The elements will get a class in the form of id-processed.
 *   Otherwise, this acts as a unique identifier; the id will be a generated
 *   number. If it's a function, it will additionally be called for each
 *   element using .each().
 * @param fn
 *   (Optional) If given, this function will be called for each element that
 *   has not yet been processed. The function should not return a value.
 *
 * @version 1.1
 * @see http://plugins.jquery.com/project/once
 *
 * Copyright (c) 2009 Konstantin Kaefer <mail@kkaefer.com>
 * Dual licensed under the MIT and GPL licenses.
 */
(function(c){var a={},b=0;c.fn.once=function(g,e){if(typeof g!="string"){if(!(g in a)){a[g]=++b}if(!e){e=g}g="jquery-once-"+a[g]}var d=g+"-processed",f=this.not("."+d).addClass(d);return c.isFunction(e)?f.each(e):f}})(jQuery);

/**
 * Type
 */
jQuery.extend(jQuery, {
	type: function(_l,_c) {
		var _n=1;
		if (_c&&_c.charAt(0)=='!') {
			_n=-1;
			_c=_c.substr(1);
		}
		switch(typeof _l) {
			case 'function': return _c?_c.indexOf('f')*_n>=0:'function';
			case 'number': return _c?_c.indexOf('n')*_n>=0:'number';
			case 'string': return _c?_c.indexOf('s')*_n>=0:'string';
			case 'undefined': return _c?_c.indexOf('u')*_n>=0:'';
			case 'object':
				if (_l instanceof Array) return _c?_c.indexOf('a')*_n>=0:'array';
				if (_l instanceof Boolean) return _c?_c.indexOf('b')*_n>=0:'boolean';
				if (_l instanceof Date) return _c?_c.indexOf('d')*_n>=0:'date';
				if (_l instanceof Image) return _c?_c.indexOf('i')*_n>=0:'image';
				if (_l instanceof RegExp) return _c?_c.indexOf('r')*_n>=0:'regexp';
				if (typeof _c=='function') return _c?_l instanceof _c:_l.constructor;
				return _c?_c.indexOf('h')*_n>=0:'hash';
		}
	}
});

/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/08/13
 *
 * @author Blair Mitchelmore
 * @version 1.1.3
 *
 **/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;

			if (jQuery.isFunction(label)) {
				if (!times)
					times = fn;
				fn = label;
				label = interval;
			}

			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}

			times = times || 0;
			belay = belay || false;

			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});

			if (!timers[label])
				timers[label] = {};

			fn.timerID = fn.timerID || this.guid++;

			var handler = function() {
				if (belay && this.inProgress)
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};

			handler.timerID = fn.timerID;

			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);

			this.global.push( element );

		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;

			if ( timers ) {

				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}

					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}

				for ( ret in timers ) break;
				if ( !ret )
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});

/**
 *  Uniq Plugin
 */
(function($) {
  $.uniq = function(notUniqArray) {
    // Check that we were given an array
    // If not, return the object
    if (!$.isArray(notUniqArray)) return notUniqArray;

    // Add each array value as a key in a map
    var map = {};
    for (var index in notUniqArray) {
      value = notUniqArray[index];
      // Store type_value as a map key,
      // unless 5 and '5' would be the same as a map key
      map[typeof value + '_' + value] = value;
    }

    // Build a new array with each map keys
    var uniqValues = [];
    for (var key in map) {
      uniqValues.push(map[key]);
    }

    return uniqValues;
  };
})(jQuery);

/* ===========================================================================
 *
 * JQuery URL Parser
 * Version 1.0
 * Parses URLs and provides easy access to information within them.
 *
 * Author: Mark Perkins
 * Author email: mark@allmarkedup.com
 *
 * For full documentation and more go to http://projects.allmarkedup.com/jquery_url_parser/
 *
 * ---------------------------------------------------------------------------
 *
 * CREDITS:
 *
 * Parser based on the Regex-based URI parser by Steven Levithan.
 * For more information (including a detailed explaination of the differences
 * between the 'loose' and 'strict' pasing modes) visit http://blog.stevenlevithan.com/archives/parseuri
 *
 * ---------------------------------------------------------------------------
 *
 * LICENCE:
 *
 * Released under a MIT Licence. See licence.txt that should have been supplied with this file,
 * or visit http://projects.allmarkedup.com/jquery_url_parser/licence.txt
 *
 * ---------------------------------------------------------------------------
 *
 * EXAMPLES OF USE:
 *
 * Get the domain name (host) from the current page URL
 * jQuery.url.attr("host")
 *
 * Get the query string value for 'item' for the current page
 * jQuery.url.param("item") // null if it doesn't exist
 *
 * Get the second segment of the URI of the current page
 * jQuery.url.segment(2) // null if it doesn't exist
 *
 * Get the protocol of a manually passed in URL
 * jQuery.url.setUrl("http://allmarkedup.com/").attr("protocol") // returns 'http'
 *
 */
jQuery.url=function(){var e={};var b={};var d={url:window.location,strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var c=function(){str=decodeURI(d.url);var j=d.parser[d.strictMode?"strict":"loose"].exec(str);var l={};var k=14;while(k--){l[d.key[k]]=j[k]||""}l[d.q.name]={};l[d.key[12]].replace(d.q.parser,function(m,i,n){if(i){l[d.q.name][i]=n}});return l};var f=function(i){if(!b.length){a()}if(i=="base"){if(b.port!==null&&b.port!==""){return b.protocol+"://"+b.host+":"+b.port+"/"}else{return b.protocol+"://"+b.host+"/"}}return(b[i]==="")?null:b[i]};var h=function(i){if(!b.length){a()}return(b.queryKey[i]===null)?null:b.queryKey[i]};var a=function(){b=c();g()};var g=function(){var i=b.path;e=[];e=b.path.length==1?{}:(i.charAt(i.length-1)=="/"?i.substring(1,i.length-1):path=i.substring(1)).split("/")};return{setMode:function(i){strictMode=i=="strict"?true:false;return this},setUrl:function(i){d.url=i===undefined?window.location:i;a();return this},segment:function(i){if(!b.length){a()}if(i===undefined){return e.length}return(e[i]===""||e[i]===undefined)?null:e[i]},attr:f,param:h}}();

/*!
 * postMessage - v0.5 - 9/11/2009
 * http://benalman.com/
 *
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Licensed under the MIT license
 * http://benalman.com/about/license/
 */

// Script: postMessage
//
// Version: 0.5, Date: 9/11/2009
//
// Tested with jQuery 1.3.2 in Internet Explorer 6-8, Firefox 3, Safari 3-4,
// Chrome, Opera 9.
//
// Home       - http://benalman.com/projects/jquery-postmessage-plugin/
// Source     - http://benalman.com/code/javascript/jquery/jquery.ba-postmessage.js
// (Minified) - http://benalman.com/code/javascript/jquery/jquery.ba-postmessage.min.js (0.9kb)
// Example    - http://benalman.com/code/test/js-jquery-postmessage/
//
//
// About: License
//
// Copyright (c) 2009 "Cowboy" Ben Alman
//
// Licensed under the MIT license
//
// http://benalman.com/about/license/
//
// Topic: What this plugin does
//
// With the addition of the window.postMessage method, JavaScript finally has a
// fantastic means for cross-domain frame communication. Unfortunately, this
// method isn't supported in all browsers. This jQuery plugin enables simple and
// easy window.postMessage communication in browsers that support it (FF3,
// Safari 4, IE8), while falling back to a document.location.hash communication
// method for all other browsers (IE6, IE7, Opera). One example where this is
// useful is when a child Iframe needs to tell its parent that its contents have
// resized.
//
// About: Revision History
//
// 0.5 - Improved cache busting
// 0.4 - Initial release

(function($){
  '$:nomunge'; // Used by YUI compressor.

  // A few vars used in non-awesome browsers.
  var interval_id,
    last_hash,
    cache_bust = 1,

    // A var used in awesome browsers.
    rm_callback,

    // A few convenient shortcuts.
    window = this,
    FALSE = !1,

    // Reused internal strings.
    postMessage = 'postMessage',
    addEventListener = 'addEventListener',

    p_receiveMessage,

    // I couldn't get window.postMessage to actually work in Opera 9.64!
    has_postMessage = window[postMessage] && !$.browser.opera;

  // Method: jQuery.postMessage
  //
  // This method will call window.postMessage if available, setting the
  // targetOrigin parameter to the base of the target_url parameter for maximum
  // security in browsers that support it. If window.postMessage is not available,
  // the target window's location.hash will be used to pass the message. If an
  // object is passed as the message param, it will be serialized into a string
  // using the jQuery.param method.
  //
  // Usage:
  //
  //  jQuery.postMessage( message, target_url [, target ] );               - -
  //
  // Arguments:
  //
  //  message - (String or Object) The window.postMessage method only supports a
  //    string message, but if an object is passed it will be serialized using
  //    the jQuery.param method.
  //  target_url - (String) The URL of the other frame this window is
  //    attempting to communicate with. This must be the exact URL (including
  //    query string) of the other window for this script to work in browsers
  //    that don't support window.postMessage.
  //  target - (Object) A reference to the other frame this window is
  //    attempting to communicate with. If unspecified, defaults to parent.
  //
  // Returns:
  //
  //  Nothing.

  $[postMessage] = function( message, target_url, target ) {
    if ( !target_url ) { return; }

    // Serialize the message if not a string. Note that this is the only real
    // jQuery dependency for this script. If removed, this script could be
    // written as very basic JavaScript.
    message = typeof message === 'string' ? message : $.param( message );

    // Default to parent if unspecified.
    target = target || parent;

    if ( has_postMessage ) {
      // The browser supports window.postMessage, so call it with a targetOrigin
      // set appropriately, based on the target_url parameter.
      target[postMessage]( message, target_url.replace( /([^:]+:\/\/[^\/]+).*/, '$1' ) );

    } else if ( target_url ) {
      // The browser does not support window.postMessage, so set the location
      // of the target to target_url#message. A bit ugly, but it works! A cache
      // bust parameter is added to ensure that repeat messages trigger the
      // callback.
      target.location = target_url.replace( /#.*$/, '' ) + '#' + (+new Date) + (cache_bust++) + '&' + message;
    }
  };

  // Method: jQuery.receiveMessage
  //
  // Register a single callback for either a window.postMessage call, if
  // supported, or if unsupported, for any change in the current window
  // location.hash. If window.postMessage is supported and source_origin is
  // specified, the source window will be checked against this for maximum
  // security. If window.postMessage is unsupported, a polling loop will be
  // started to watch for changes to the location.hash.
  //
  // Note that for simplicity's sake, only a single callback can be registered
  // at one time. Passing no params will unbind this event (or stop the polling
  // loop), and calling this method a second time with another callback will
  // unbind the event (or stop the polling loop) first, before binding the new
  // callback.
  //
  // Usage:
  //
  //  jQuery.receiveMessage( callback [, source_origin ] [, delay ] );       - -
  //
  // Arguments:
  //
  //  callback - (Function) This callback will execute whenever a <jQuery.postMessage>
  //    message is received, provided the source_origin matches. If callback is
  //    omitted, any existing event bind or polling loop will be canceled.
  //  source_origin - (String or Function) If window.postMessage is available,
  //    this optional param will be used to test the event.origin property. If
  //    the param is a string, and is not equal to the event.origin property, or
  //    a function that returns false when passed the event.origin property, the
  //    callback will not be called. From the MDC window.postMessage docs:
  //    This string is the concatenation of the protocol and "://", the host
  //    name if one exists, and ":" followed by a port number if a port is
  //    present and differs from the default port for the given protocol.
  //    Examples of typical origins are https://example.org (implying port 443),
  //    http://example.net (implying port 80), and http://example.com:8080.
  //  delay - (Number) An optional zero-or-greater delay in milliseconds at
  //    which the polling loop will execute (for browser that don't support
  //    window.postMessage). If unspecified, defaults to 100.
  //
  // Returns:
  //
  //  Nothing!

  $.receiveMessage = p_receiveMessage = function( callback, source_origin, delay ) {
    if ( has_postMessage ) {
      // Since the browser supports window.postMessage, the callback will be
      // bound to the actual event associated with window.postMessage.

      if ( callback ) {
        // Unbind an existing callback if it exists.
        rm_callback && p_receiveMessage();

        // Bind the callback. A reference to the callback is stored for ease of
        // unbinding.
        rm_callback = function(e) {
          if ( ( typeof source_origin === 'string' && e.origin !== source_origin )
            || ( $.isFunction( source_origin ) && source_origin( e.origin ) === FALSE ) ) {
            return FALSE;
          }
          callback( e );
        };
      }

      if ( window[addEventListener] ) {
        window[ callback ? addEventListener : 'removeEventListener' ]( 'message', rm_callback, FALSE );
      } else {
        window[ callback ? 'attachEvent' : 'detachEvent' ]( 'onmessage', rm_callback );
      }

    } else {
      // Since the browser sucks, a polling loop will be started, and the
      // callback will be called whenever the location.hash changes.

      interval_id && clearInterval( interval_id );
      interval_id = null;

      if ( callback ) {
        delay = typeof source_origin === 'number'
          ? source_origin
          : typeof delay === 'number'
            ? delay
            : 100;

        interval_id = setInterval(function(){
          var hash = document.location.hash,
            re = /^#?\d+&/;
          if ( hash !== last_hash && re.test( hash ) ) {
            last_hash = hash;
            callback({ data: hash.replace( re, '' ) });
          }
        }, delay );
      }
    }
  };

})(jQuery);

/**
 * Logger
 */
(function($) {
  $.log = function() {
    appendLogEntry(log_queue, arguments);
    if ($.log.settings.logToConsole) {
      try { browser_logger.apply(null, arguments); } catch(_) {}
    }
    return $.log;
  };

  $.log.log = $.log; // for chained logs $.log().log(), rather than $.log()()

  $.log.report = function(mode) {
    report(log_queue, mode);
  };

  $.log.trace = function() {
    browser_trace();
    return $.log;
  };

  $.log.profile = function() {
    if (window.console) {
      if (!arguments.length || "start" == arguments[0]) {
        try { console.profile(); } catch(_) {}
      } else if ("stop" == arguments[0]) {
        try { console.profileEnd(); } catch(_) {}
      }
    }
    return $.log;
  };

  $.fn.log = function() {
    var domLog = $(this).data("log_queue");
    if (!domLog) {
      domLog = [];
      $(this).data("log_queue", domLog);
    }
    appendLogEntry(domLog, arguments);
    $.log.apply(null, arguments);
    return this;
  };

  $.fn.logReport = function(mode) {
    report($(this).data("log_queue"), mode);
    return this;
  };

  var detectBrowserLoggingFunctions = function() {
    if (window.console) {
      browser_logger = console.log || console.debug || console.info || console.warn || console.error;
      if (console.trace) {
        browser_trace = console.trace;
      } else {
        // make our own
        // appendLogEntry(log_queue, ?);
      }
      return true;
    }
    return false;
  };

  var report = function(log, mode) {
    if (pollForConsole) {
      pollForConsole = !detectBrowserLoggingFunctions();
      if (pollForConsole) {
        return;
      }
    }

    if (mode && $.log.report.hasOwnProperty(mode) && $.isFunction($.log.report[mode])) {
      $.log.report[mode](log, browser_logger);
    } else {
      $.log.report.basic(log, browser_logger);
    }
  };

  var appendLogEntry = function(log, data) {
    log.push({ timestamp: (new Date()).getTime(), data: data });
    if (-1 == $.inArray(log, trim_queue)) {
      trim_queue.push(log);
    }
    if (!trim_timer) {
      trim_timer = setTimeout(trimQueues, $.log.settings.minEntryDuration);
    }
  };

  var trimQueues = function() {
    var maxTS = (new Date()).getTime() - $.log.settings.maxEntryDuration;
    var minTS = (new Date()).getTime() - $.log.settings.minEntryDuration;
    for (var i = 0; i < trim_queue.length; ++i) {
      var maxEntries = (trim_queue[i] == log_queue) ? $.log.settings.maxGlobalEntries : $.log.settings.maxDomEntries;
      for (var trimPoint1 = 0; trimPoint1 < trim_queue[i].length && trim_queue[i][trimPoint1].timestamp < maxTS; ++trimPoint1) {}
      for (var trimPoint = Math.max(trimPoint1 - 1, trim_queue[i].length - maxEntries); trimPoint > 0 && trim_queue[i][trimPoint].timestamp > minTS; --trimPoint){}
      if (trimPoint > 0) {
        //console.debug("trimming first %d log entries", trimPoint + 1);
        trim_queue[i].splice(0, trimPoint + 1);
      }
      if (!trim_queue[i].length) {
        trim_queue.splice(i, 1);
        --i;
      }
    }

    if (pollForConsole && window.console) {
      pollForConsole = !detectBrowserLoggingFunctions();
      if (!pollForConsole && $.log.settings.logToConsole) {
        report(log_queue);
      }
    }

    if (trim_queue.length) {
      trim_timer = setTimeout(trimQueues, $.log.settings.trimInterval);
    } else {
      trim_timer = null;
    }
  };

  var log_queue = [];
  var trim_queue = [];
  var trim_timer;
  var browser_logger = function(){};
  var browser_trace = function(){};
  var pollForConsole = !detectBrowserLoggingFunctions();

  $.log.report.basic = function(log, logger) {
    for (var i = 0; i < log.length; ++i) {
      logger.apply(null, $.makeArray(log[i].data));
    }
  };
  $.log.report.details = function(log, logger) {
    for (var i = 0; i < log.length; ++i) {
      logger.apply(null, [(new Date(log[i].timestamp)).toLocaleString(), ": "].concat($.makeArray(log[i].data)));
    }
  };
  /*$.log.report.hierarchy = function(log, logger) {
    if (log.length) {
      var createNode = function(entry, parent) {
        return { parent: parent, children: [entry], func: entry.data.callee, hasChildNodes: false };
      };
      var getCurNode = function(node, func) {
        var backFunc = func;
        while (backFunc) {
          if (backFunc = node.func) {
            return node;
          }
          backFunc = backFunc.caller;
        }
        if (node.parent) {
          return getCurNode(node.parent, func);
        }
        return node;
      };
      var top, cur;
      top = cur = { parent: null, children: [], func: null, hasChildNodes: false };
      for (var i = 0; i < log.length; ++i) {
        cur = getCurNode(cur, log[i].data.callee);
        if (cur.func == log[i].data.callee) {
          cur.children.push(log[i]);
        } else {
          var newNode = createNode(log[i], cur);
          cur.children.push(newNode);
          cur.hasChildNodes = true;
          cur = newNode;
        }
      }
      var print = function(node) {
        if (node.hasChildNodes) {
          (console.group || logger).call(null, "");
        }
        for (var i = 0; i < node.children.length; ++i) {
          if (node.children[i].children) {
            print(node.children[i]);
          } else {
            logger.apply(null, [].splice.call(node.children[i].data, 0));
          }
        }
        if (node.hasChildNodes) {
          try { console.groupEnd(); } catch(_) {}
        }
      };
      print(top);
    }
  };*/

  $.log.settings = {
    maxGlobalEntries: 1000,
    maxDomEntries: 50,
    maxEntryDuration: 3600000,
    minEntryDuration: 15000,
    trimInterval: 5000,
    logToConsole: false
  };
})(jQuery);

/**
 * ID Plugin
 */
(function($) {
  $.fn.id = function(newid) {
    if ("undefined" != typeof newid) {
      $(this).attr("id", newid);
    } else {
      return $(this).attr("id");
    }
  };
})(jQuery);

/** Copyright (c) 2007 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2008-05-09 09:24:44 -0500 (Fri, 09 May 2008) $
 * $Rev: 5535 $
 *
 * Version: 1.0.1
 */
(function($){

$.fn.batch = function(method) {
	var args = $.makeArray(arguments).slice(1), results = [];
	this.each(function() {
		results.push( $(this)[method].apply($(this), args) );
	});
	return results;
};

$.batch = {
	version: "1.0.1",
	registerPlugin: function() {
		$.each( arguments, function( index, plugin ) {
			var method = plugin.constructor == Array && plugin[0] || plugin,
				newMethod = plugin.constructor == Array && plugin[1] || plugin+"s";
			if ( $.fn[ method ] && !$.fn[ newMethod ] )
				$.fn[ newMethod ] = function() {
					return this.batch.apply( this, [ method ].concat( $.makeArray(arguments) ) );
				};
		});
	}
};

$.batch.registerPlugin( 'attr', ['css','styles'], 'offset', 'width', 'height', 'html', 'text', 'val' );

// Gilt Modification:
$.batch.registerPlugin('id');

})(jQuery);

/*
 * Metadata - jQuery plugin for parsing metadata from elements
 *
 * Copyright (c) 2006 John Resig, Yehuda Katz, J?šrn Zaefferer, Paul McLanahan
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.metadata.js 3640 2007-10-11 18:34:38Z pmclanahan $
 *
 * Sets the type of metadata to use. Metadata is encoded in JSON, and each property
 * in the JSON will become a property of the element itself.
 *
 * There are four supported types of metadata storage:
 *
 *   attr:  Inside an attribute. The name parameter indicates *which* attribute.
 *
 *   class: Inside the class attribute, wrapped in curly braces: { }
 *
 *   elem:  Inside a child element (e.g. a script tag). The
 *          name parameter indicates *which* element.
 *   html5: Values are stored in data-* attributes.
 *
 * The metadata for an element is loaded the first time the element is accessed via jQuery.
 *
 * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
 * matched by expr, then redefine the metadata type and run another $(expr) for other elements.
 *
 * @name $.metadata.setType
 *
 * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("class")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from the class attribute
 *
 * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("attr", "data")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a "data" attribute
 *
 * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
 * @before $.metadata.setType("elem", "script")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a nested script element
 *
 * @example <p id="one" class="some_class" data-item_id="1" data-item_label="Label">This is a p</p>
 * @before $.metadata.setType("html5")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a series of data-* attributes
 *
 * @param String type The encoding type
 * @param String name The name of the attribute to be used to get metadata (optional)
 * @cat Plugins/Metadata
 * @descr Sets the type of encoding to be used when loading metadata for the first time
 * @type undefined
 * @see metadata()
 */

(function($) {

$.extend({
  metadata : {
    defaults : {
      type: 'class',
      name: 'metadata',
      cre: /({.*})/,
      single: 'metadata'
    },
    setType: function( type, name ){
      this.defaults.type = type;
      this.defaults.name = name;
    },
    get: function( elem, opts ){
      var settings = $.extend({},this.defaults,opts);
      // check for empty string in single property
      if ( !settings.single.length ) settings.single = 'metadata';

      var data = $.data(elem, settings.single);
      // returned cached data if it already exists
      if ( data ) return data;

      data = "{}";

      var getData = function(data) {
        if(typeof data != "string") return data;

        if( data.indexOf('{') < 0 ) {
          data = eval("(" + data + ")");
        }
      };

      var getObject = function(data) {
        if(typeof data != "string") return data;

        data = eval("(" + data + ")");
        return data;
      };

      if ( settings.type == "html5" ) {
        var object = {};
        $( elem.attributes ).each(function() {
          var name = this.nodeName;
          if(name.match(/^data-/)) name = name.replace(/^data-/, '');
          else return true;
          object[name] = getObject(this.nodeValue);
        });
      } else {
        if ( settings.type == "class" ) {
          var m = settings.cre.exec( elem.className );
          if ( m )
            data = m[1];
        } else if ( settings.type == "elem" ) {
          if( !elem.getElementsByTagName ) return;
          var e = elem.getElementsByTagName(settings.name);
          if ( e.length )
            data = $.trim(e[0].innerHTML);
        } else if ( elem.getAttribute != undefined ) {
          var attr = elem.getAttribute( settings.name );
          if ( attr )
            data = attr;
        }
        object = getObject(data.indexOf("{") < 0 ? "{" + data + "}" : data);
      }

      $.data( elem, settings.single, object );
      return object;
    }
  }
});

/**
 * Returns the metadata object for the first member of the jQuery object.
 *
 * @name metadata
 * @descr Returns element's metadata object
 * @param Object opts An object contianing settings to override the defaults
 * @type jQuery
 * @cat Plugins/Metadata
 */
$.fn.metadata = function( opts ){
  return $.metadata.get( this[0], opts );
};

})(jQuery);

/**
 * Caret Plugin
 */
(function($) {
  $.fn.caret = function(pos) {
    var target = this[0];
    if (arguments.length == 0) { //get
      if (target.selectionStart) { //DOM
        pos = target.selectionStart;
        return pos > 0 ? pos : 0;
      }
      else if (target.createTextRange) { //IE
        target.focus();
        var range = document.selection.createRange();
        if (range == null)
          return '0';
        var re = target.createTextRange();
        var rc = re.duplicate();
        re.moveToBookmark(range.getBookmark());
        rc.setEndPoint('EndToStart', re);
        return rc.text.length;
      }
      else return 0;
    } //set
    if (target.setSelectionRange) //DOM
      target.setSelectionRange(pos, pos);
    else if (target.createTextRange) { //IE
      range = target.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  };
})(jQuery);

/**
 * Unique Selector
 *
 * @version 0.5
 * @requires jQuery v1.3
 * @author Kevan Davis
 * @copyright Copyright (c) 2009, Gilt Groupe
 *
 * Distributed under the terms of the GNU General Public License
 * http://www.gnu.org/licenses/gpl-3.0.html
 *
 * Calculates a unique css selector for an element
 *
 * Attempts have been made to optimize the selector, but it's far from perfect
 */
(function($) {
  var helper = function(el, first) {
    var path = "";
    if (el.attr("id")) {
      return "#" + el.attr ("id"); // If it has an id, no need for anything above this point, since ids are required to be unique
    } else {
      path = el[0].nodeName.toLowerCase(); // get the nodename, e.g. "div"
      if (el.attr("class")) {
        path += "." + el.attr("class").split(" ")[0]; // if it has a class, append it, e.g. "div.mydiv"
      }
      if (el.prevAll(path).length || el.nextAll(path).length) { // if there are multiple such elements at this level, append an index, e.g. "div.mydiv:eq(7)"
        path += ":eq(" + el.prevAll(path).length + ")";
      }
    }
    if (el.parent().length) { // in an (x)html document, should always return true, since we never reach the Document itself.  in XML, it will return false for the root element
      if (el.parent()[0] == $("body")[0]) {
        return "body " + path;
      } else if (el.parent()[0] == $("head")[0]) {
        return "head " + path;
      } else if (el.parent()[0] == $("html")[0]) {
        if (el[0].nodeName.toLowerCase() == "body") {
          return "body";
        } else if (el[0].nodeName.toLowerCase() == "head") {
          return "head";
        }
        return "html " + path;
      } else if (!first) { // ok, we're not at the top, and we're not at the bottom
        if (!el.siblings().length) { // if we're an only child, no need to be included
          return helper(el.parent(), false) + "!"; // appending a "!", we look for this afterwords, and remove it and any ">" that follows
        }
      }
      return helper(el.parent(), false) + ">" + path;
    }
    return path;
  };
  $.fn.getUniqueSelector = function() {
    return helper(this, true).replace(/!+>?/g, " ");
  };
})(jQuery);

/**
 * Start/End of Line Selectors
 *
 * @version 0.9
 * @requires jQuery v1.3
 * @author: Kevan Davis (kdavis@gilt.com)
 * @copyright Copyright (c) 2009, Gilt Groupe
 *
 * Distributed under the terms of the GNU General Public License
 * http://www.gnu.org/licenses/gpl-3.0.html
 *
 **/
(function($){
  $.extend($.fn, {
    startOfLine: function(strict) {
      var elements = this;
      var targets = [];
      var i = -1;
      var max = elements.length;

      while (++i < max) {
        var el = $(elements[i]);
        var el_top = el.offset().top - parseInt(el.css("margin-top"));
        var sibs = el.prevAll();
        var j = -1;
        var end = sibs.length;
        var target = el;
        var candidate;

        while (++j < end) {
          candidate = sibs.eq(j);
          var c_bottom = candidate.offset().top + candidate.height() + parseInt(candidate.css("margin-bottom"));
          if (el_top < c_bottom) {
            if (strict) {
              var c_top = candidate.offset().top - parseInt(candidate.css("margin-top"));
              if (c_top >= el_top) {
                target = candidate;
              }
            } else {
              target = candidate;
            }
          }
        }
        targets.push(target.get(0));
      }
      return $(targets);
    },
    endOfLine: function(strict, lazy) {
      var elements = this;
      var targets = [];
      var i = -1;
      var max = elements.length;

      while (++i < max) {
        var el = $(elements[i]);
        var el_bottom = el.offset().top + el.height() + parseInt(el.css("margin-bottom"));
        var sibs = el.nextAll();
        var j = sibs.length;
        var target = el;
        var candidate;

        while (j--) {
          candidate = sibs.eq(j);
          var c_top = candidate.offset().top - parseInt(candidate.css("margin-top"));
          if (c_top < el_bottom) {
            if (strict) {
              var c_bottom = candidate.offset().top + candidate.height() + parseInt(candidate.css("margin-bottom").replace(/px/i,''));
              if (c_bottom <= el_bottom) {
                target = candidate;
              }
            } else {
              target = candidate;
            }
          }
        }
        targets.push(target.get(0));
      }
      return $(targets);
    }
  });
})(jQuery);

/*
 * Viewport - jQuery selectors for finding elements in viewport
 *
 * Copyright (c) 2008-2009 Mika Tuupola
 * Copyright (c) 2009 Kevan Davis, Gilt Groupe
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   http://www.appelsiini.net/projects/viewport
 *
 * Gilt Groupe Modification:
 *   Added :below(selector), :above(selector), :right-of(selector), :left-of(selector),
 *   :with-in(selector) selectors.  Behave same as existing selectors, but relative to
 *   the first element returned by a selector.  :with-in requires that part of the
 *   matched element be within the selected element.
 */
(function($) {
  $.belowthefold = function(element, settings) {
    return $.below(element, window, settings);
  };

  $.abovethetop = function(element, settings) {
    return $.above(element, window, settings);
  };

  $.rightofscreen = function(element, settings) {
    return $.rightof(element, window, settings);
  };

  $.leftofscreen = function(element, settings) {
    return $.leftof(element, window, settings);
  };

  $.inviewport = function(element, settings) {
    return $.within(element, window, settings);
  };

  $.below = function(element1, element2, settings) {
    var bottom = $(element2).height() + $(element2).scrollTop();
    return bottom <= $(element1).offset().top - settings.threshold;
  };

  $.above = function(element1, element2, settings) {
    var top = $(element2).scrollTop();
    return top >= $(element1).offset().top + $(element1).height() - settings.threshold;
  };

  $.rightof = function(element1, element2, settings) {
    var right = $(element2).width() + $(element2).scrollLeft();
    return right <= $(element1).offset().left - settings.threshold;
  };

  $.leftof = function(element1, element2, settings) {
    var left = $(element2).scrollLeft();
    return left >= $(element1).offset().left + $(element1).width() - settings.threshold;
  };

  $.within = function(element1, element2, settings) {
    return !$.rightof(element1, element2, settings) && !$.leftof(element1, element2, settings) && !$.below(element1, element2, settings) && !$.above(element1, element2, settings);
  };

  $.extend($.expr[':'], {
    "below-the-fold": function(a, i, m) {
      return $.below(a, window, {threshold : 0});
    },
    "above-the-top": function(a, i, m) {
      return $.above(a, window, {threshold : 0});
    },
    "left-of-screen": function(a, i, m) {
      return $.leftof(a, window, {threshold : 0});
    },
    "right-of-screen": function(a, i, m) {
      return $.rightof(a, window, {threshold : 0});
    },
    "in-viewport": function(a, i, m) {
      return $.inview(a, window, {threshold : 0});
    },
    "below": function(a, i, m) {
      return $.below(a, m, {threshold : 0});
    },
    "above": function(a, i, m) {
      return $.above(a, m, {threshold : 0});
    },
    "left-of": function(a, i, m) {
      return $.leftof(a, m, {threshold : 0});
    },
    "right-of": function(a, i, m) {
      return $.rightof(a, m, {threshold : 0});
    },
    "with-in": function(a, i, m) {
      return $.within(a, m, {threshold : 0});
    }
  });
})(jQuery);



/**
 * Bound Event(s) Plugin
 *
 * @version 0.9
 * @requires jQuery v1.3
 * @author Kevan Davis
 * @copyright Copyright (c) 2009, Gilt Groupe
 *
 * Distributed under the terms of the GNU General Public License
 * http://www.gnu.org/licenses/gpl-3.0.html
 *
 * @description :
 *
 * Returns an array of events bound to an element
 * If a type is passed in, returns only those types.
 *
 * CSS Pseudo Selector :bound(eventType) returns elements that have events of a certain type
 *
 * Also supports namespaced events
 *
 * @usage :
 * $('#blah').bound('click') -- returns all functions bound to the click event on #blah
 * $('#blah').bound() -- returns all functions bound to any event on #blah
 * $('.blah').bound('.test') -- returns all functions bound to the test namespace on the first element with class blah
 * $('.blah:bound(click.test)') -- returns all elements with class blah that have a click handler in namespace test
 */
(function($) {
  $.fn.bound = function(type) {
    var namespace = null;
    if (0 == type.indexOf(".")) {
      namespace = type.substr(1);
      type = null;
    } else if(-1 != type.indexOf(".")) {
      var p = type.split(".");
      namespace = p[1];
      type = p[0];
    }
    var events = $(this).data("events");
    if (!events) {
      return [];
    }
    if (type) {
      events = events[type]||{};
    } else {
      var old = events;
      events = {};
      for (var group in old) {
        if (old.hasOwnProperty(group)) {
          $.extend(events, old[group]);
        }
      }
    }
    var eventsArray = [];
    for (var e in events) {
      if (events.hasOwnProperty(e)) {
        if (!namespace || events[e].type == namespace) {
          eventsArray.push(events[e]);
        }
      }
    }
    return eventsArray;
  };
  $.extend($.expr[":"], {
    "bound": function(a, i, m) {
      var found = false;
      if (m && m[3]) {
        var events = m[3].split(",");
        var j = events.length;
        while (j--) {
          if ($(a).bound(events[j]).length) {
            found = true;
            break;
          }
        }
      } else {
        if ($(a).bound().length) {
          found = true;
        }
      }
      return found;
    }
  });
})(jQuery);

/*
	Unwrap extension for jQuery
	Version: 1.1

	Copyright (c) 2009 Todd Northrop
	http://www.speednet.biz/

	June 7, 2009

	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, 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.

	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/>.
------------------------------------------------------*/

jQuery.fn.unwrap = function (selector) {
	///	<summary>
	///		Removes the immediate parent wrapping element from each element of the matched set.
	/// 	For elements in the matched set that share a common parent, the common parent element
	/// 	is removed.
	///	</summary>
	///	<returns type="jQuery">
	///		Returns the original jQuery matched set.
	/// </returns>
	/// <remarks>
	/// 	To keep things simple, I have avoided adding a selector argument to this extension.
	/// 	I suppose I could add it, but perhaps that is best done with a .filter() before
	/// 	calling .unwrap(). If you have an opinion about this, let me know.
	///
	/// 	New for version 1.1, elements in the wrapped set that are direct children of the
	/// 	body tag will not be unwrapped, because doing so would delete the body tag.
	/// </remarks>

	return this.parent(":not(body)").filter(selector || "*").each(
		function () {
			var $set = jQuery(this);
			$set.replaceWith($set.contents());
		}
	).end();
};

/*
 * JQuery strftime plugin
 * Version 1.0.1 (12/06/2008)
 *
 * No documentation at this point, sorry.
 *
 * Home page: http://projects.nocternity.net/jquery-strftime/
 * Examples: http://projects.nocternity.net/jquery-strftime/demo.html
 *
 * Copyright (c) 2008 Emmanuel Beno”t
 *
 * 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.
 */

$(function(){

 var _defaults = {
   'days_short' : [ 'Sun', 'Mon' , 'Tue' , 'Wed' , 'Thu' ,
       'Fri' , 'Sat' ] ,
   'days_long' : [ 'Sunday' , 'Monday' , 'Tuesday' ,
       'Wednesday' , 'Thursday' , 'Friday' ,
       'Saturday' ] ,
   'months_short' : [ 'Jan' , 'Feb' , 'Mar' , 'Apr' ,
       'May' , 'Jun' , 'Jul' , 'Aug' ,
       'Sep' , 'Oct' , 'Nov' , 'Dec' ] ,
   'months_long' : [ 'January' , 'February' , 'March' ,
       'April' , 'May' , 'June' , 'July' ,
       'August' , 'September' , 'October' ,
       'November' , 'December' ] ,
   'format' : '%m/%d/%Y'
 };

 var _useText = _defaults;

 var _finaliseObj = function ( _obj , _month , _dow ) {
   _obj.a = _useText.days_short[ _dow ];
   _obj.A = _useText.days_long[ _dow ];
   _obj.b = _useText.months_short[ _month ];
   _obj.B = _useText.months_long[ _month ];
   _obj.m = _month + 1;

   var _tmp;

   if ( _obj.Y > 0 ) {
     _tmp = _obj.Y.toString( );
     if ( _tmp.length < 2 ) {
       _tmp = '0' + _tmp;
     } else if ( _tmp.length > 2 ) {
       _tmp = _tmp.substring( _tmp.length - 2 );
     }
     _obj.y = _tmp;
   } else {
     _obj.y = _obj.Y;
   }

   var _check = [ 'd' , 'm' , 'H' , 'M' , 'S' ];
   for ( var i in _check ) {
     _tmp = _obj[ _check[ i ] ];
     _tmp = _tmp.toString( );
     if ( _tmp.length < 2 ) {
       _tmp = '0' + _tmp;
     }
     _obj[ _check[ i ] ] = _tmp;
   }

   return _obj;
 };

 var _dateTimeToDtObj = function ( dateTime , utc ) {
   var _obj, _month, _dow;
   if ( utc ) {
     _obj = {
       'H' : dateTime.getUTCHours( ) ,
       'M' : dateTime.getUTCMinutes( ) ,
       'S' : dateTime.getUTCSeconds( ) ,
       'd' : dateTime.getUTCDate( ) ,
       'Y' : dateTime.getUTCFullYear( )
     };
     _month = dateTime.getUTCMonth( );
     _dow = dateTime.getUTCDay( );
   } else {
     _obj = {
       'H' : dateTime.getHours( ) ,
       'M' : dateTime.getMinutes( ) ,
       'S' : dateTime.getSeconds( ) ,
       'd' : dateTime.getDate( ) ,
       'Y' : dateTime.getFullYear( )
     };
     _month = dateTime.getMonth( );
     _dow = dateTime.getDay( );
   }
   return _finaliseObj( _obj , _month , _dow );
 };

 var _objToDtObj = function ( obj ) {
   var _defs = {
     'H' : 0 ,
     'M' : 0 ,
     'S' : 0 ,
     'd' : 1 ,
     'Y' : 1 ,
     'm' : 1
   };
   var _dtObj = {};

   for ( var i in _defs ) {
     if ( typeof obj[ i ] != 'number' || obj[ i ] % 1 != 0 ) {
       _dtObj[ i ] = _defs[ i ];
     } else {
       _dtObj[ i ] = obj[ i ];
     }
   }

   _dtObj.m --;

   var _dow;
   if ( typeof obj.dow == 'number' && obj.dow % 1 == 0 ) {
     _dow = obj.dow;
   } else {
     _dow = 0;
   }

   return _finaliseObj( _dtObj , _dtObj.m , _dow );
 };

 $.strftime = function ( fmt , dateTime , utc ) {

   if ( fmt && typeof fmt == 'object' ) {
     dateTime = fmt.dateTime;
     utc = fmt.utc;
     fmt = fmt.format;
   }

   if ( !fmt || ( typeof fmt != 'string' ) ) {
     fmt = _useText.format;
   }

   var _dtObj;
   if ( dateTime && ( typeof dateTime == 'object' ) ) {
     if ( dateTime instanceof Date ) {
       _dtObj = _dateTimeToDtObj( dateTime , utc );
     } else {
       _dtObj = _objToDtObj( dateTime );
     }
   } else {
     _dtObj = _dateTimeToDtObj( new Date( ) , utc );
   }

   var _text = '' , _state = 0;
   for ( var i = 0 ; i < fmt.length ; i ++ ) {
     if ( _state == 0 ) {
       if ( fmt.charAt(i) == '%' ) {
         _state = 1;
       } else {
         _text += fmt.charAt( i );
       }
     } else {
       if ( typeof _dtObj[ fmt.charAt( i ) ] != 'undefined' ) {
         _text += _dtObj[ fmt.charAt( i ) ];
       } else {
         _text += '%';
         if ( fmt.charAt( i ) != '%' ) {
           _text += fmt.charAt( i );
         }
       }
       _state = 0;
     }
   }
   if ( _state == 1 ) {
     _text += '%';
   }

   return _text;
 };


 $.extend( $.strftime , {
   setText: function ( obj ) {
     if ( typeof obj != 'object' ) {
       throw new Error( '$.strftime.setText() : invalid parameter' );
     }

     var _count = 0;
     for ( var i in obj ) {
       if ( typeof _defaults[ i ] == 'undefined' ) {
         throw new Error( '$.strftime.setText() : invalid field "' + i + '"' );
       } else if ( i == 'format' && typeof obj[ i ] != 'string' ) {
         throw new Error( '$.strftime.setText() : invalid type for the "format" field' );
       } else if ( i != 'format' && ! ( obj[ i ] instanceof Array ) ) {
         throw new Error( '$.strftime.setText() : field "' + i + '" should be an array' );
       } else if ( obj[ i ].length != _defaults[ i ].length ) {
         throw new Error( '$.strftime.setText() : field "' + i + '" has incorrect length '
             + obj[ i ].length + ' (should be ' + _defaults[ i ].length + ')'
                );
       }
       _count ++;
     }
     if ( _count != 5 ) {
       throw new Error( '$.strftime.setText() : 5 fields expected, ' + _count + ' found' );
     }

     _useText = obj;
   },

   defaults: function ( ) {
     _useText = _defaults;
   }
 } );

 $.fn.strftime = function ( fmt , dateTime , utc ) {
   var _text = $.strftime( fmt , dateTime , utc );
   return this.each( function( ) {
     $(this).html( _text );
   });
 };

});

/**
 * jQuery Widget Plugins
 *   Includes both ui widgets, and plugins that are too large to be considered utilities.
 *   Gilt Originals have full source, other plugins are compressed (otherwise, this file would be 10000 lines long)
 *
 * TOC:
 *   (3rd Party)
 *     CoolInput
 *     qTip
 *     Form
 *     Validation
 *     Jcrop
 *     History
 *     Autocomplete
 *
 *   (Gilt Originals)
 *     Zoom
 *     Rollover
 *     Carousel
 *     Size Chart
 */

/**
 * CoolInput Plugin
 *
 * @version 1.2 (17/09/2008)
 * @requires jQuery v1.2.6
 * @author Alex Weber <alexweber.info>
 * @copyright Copyright (c) 2008, Alex Weber
 *
 * Distributed under the terms of the GNU General Public License
 * http://www.gnu.org/licenses/gpl-3.0.html
 *
 */
eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('4.g.h=1(c){5 d={8:\'i\',3:\'6\',7:j,9:k};0(c){4.l(d,c)}m e.n(1(){5 a=4(e);5 b=a.o(d.8);0(b){a.6(1(){0(a.2()==\'\'){a.2(b).f(d.3)}}).p(1(){0(a.2()==b){a.2(\'\').q(d.3)}});0(d.9){a.r(\'s:t\').u(1(){0(a.v(d.3)){a.2(\'\')}})}0(d.7){a.f(d.7)}a.6()}})};',32,32,'if|function|val|blurClass|jQuery|var|blur|iconClass|source|clearText|||||this|addClass|fn|coolinput|title|false|true|extend|return|each|attr|focus|removeClass|parents|form|first|submit|hasClass'.split('|'),0,{}));

/**
 * jquery.qtip. The jQuery tooltip plugin
 *
 * Copyright (c) 2009 Craig Thompson
 * http://craigsworks.com
 *
 * Licensed under MIT
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Launch  : February 2009
 * Version : 1.0.0-rc3
 * Released: Tuesday 12th May, 2009 - 00:00
 * Debug: jquery.qtip.debug.js
 */
(function(f){f.fn.qtip=function(B,u){var y,t,A,s,x,w,v,z;if(typeof B=="string"){if(typeof f(this).data("qtip")!=="object"){f.fn.qtip.log.error.call(self,1,f.fn.qtip.constants.NO_TOOLTIP_PRESENT,false)}if(B=="api"){return f(this).data("qtip").interfaces[f(this).data("qtip").current]}else{if(B=="interfaces"){return f(this).data("qtip").interfaces}}}else{if(!B){B={}}if(typeof B.content!=="object"||(B.content.jquery&&B.content.length>0)){B.content={text:B.content}}if(typeof B.content.title!=="object"){B.content.title={text:B.content.title}}if(typeof B.position!=="object"){B.position={corner:B.position}}if(typeof B.position.corner!=="object"){B.position.corner={target:B.position.corner,tooltip:B.position.corner}}if(typeof B.show!=="object"){B.show={when:B.show}}if(typeof B.show.when!=="object"){B.show.when={event:B.show.when}}if(typeof B.show.effect!=="object"){B.show.effect={type:B.show.effect}}if(typeof B.hide!=="object"){B.hide={when:B.hide}}if(typeof B.hide.when!=="object"){B.hide.when={event:B.hide.when}}if(typeof B.hide.effect!=="object"){B.hide.effect={type:B.hide.effect}}if(typeof B.style!=="object"){B.style={name:B.style}}B.style=c(B.style);s=f.extend(true,{},f.fn.qtip.defaults,B);s.style=a.call({options:s},s.style);s.user=f.extend(true,{},B)}return f(this).each(function(){if(typeof B=="string"){w=B.toLowerCase();A=f(this).qtip("interfaces");if(typeof A=="object"){if(u===true&&w=="destroy"){while(A.length>0){A[A.length-1].destroy()}}else{if(u!==true){A=[f(this).qtip("api")]}for(y=0;y<A.length;y++){if(w=="destroy"){A[y].destroy()}else{if(A[y].status.rendered===true){if(w=="show"){A[y].show()}else{if(w=="hide"){A[y].hide()}else{if(w=="focus"){A[y].focus()}else{if(w=="disable"){A[y].disable(true)}else{if(w=="enable"){A[y].disable(false)}}}}}}}}}}}else{v=f.extend(true,{},s);v.hide.effect.length=s.hide.effect.length;v.show.effect.length=s.show.effect.length;if(v.position.container===false){v.position.container=f(document.body)}if(v.position.target===false){v.position.target=f(this)}if(v.show.when.target===false){v.show.when.target=f(this)}if(v.hide.when.target===false){v.hide.when.target=f(this)}t=f.fn.qtip.interfaces.length;for(y=0;y<t;y++){if(typeof f.fn.qtip.interfaces[y]=="undefined"){t=y;break}}x=new d(f(this),v,t);f.fn.qtip.interfaces[t]=x;if(typeof f(this).data("qtip")=="object"){if(typeof f(this).attr("qtip")==="undefined"){f(this).data("qtip").current=f(this).data("qtip").interfaces.length}f(this).data("qtip").interfaces.push(x)}else{f(this).data("qtip",{current:0,interfaces:[x]})}if(v.content.prerender===false&&v.show.when.event!==false&&v.show.ready!==true){v.show.when.target.bind(v.show.when.event+".qtip-"+t+"-create",{qtip:t},function(C){z=f.fn.qtip.interfaces[C.data.qtip];z.options.show.when.target.unbind(z.options.show.when.event+".qtip-"+C.data.qtip+"-create");z.cache.mouse={x:C.pageX,y:C.pageY};p.call(z);z.options.show.when.target.trigger(z.options.show.when.event)})}else{x.cache.mouse={x:v.show.when.target.offset().left,y:v.show.when.target.offset().top};p.call(x)}}})};function d(u,t,v){var s=this;s.id=v;s.options=t;s.status={animated:false,rendered:false,disabled:false,focused:false};s.elements={target:u.addClass(s.options.style.classes.target),tooltip:null,wrapper:null,content:null,contentWrapper:null,title:null,button:null,tip:null,bgiframe:null};s.cache={mouse:{},position:{},toggle:0};s.timers={};f.extend(s,s.options.api,{show:function(y){var x,z;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"show")}if(s.elements.tooltip.css("display")!=="none"){return s}s.elements.tooltip.stop(true,false);x=s.beforeShow.call(s,y);if(x===false){return s}function w(){if(s.options.position.type!=="static"){s.focus()}s.onShow.call(s,y);if(f.browser.msie){s.elements.tooltip.get(0).style.removeAttribute("filter")}}s.cache.toggle=1;if(s.options.position.type!=="static"){s.updatePosition(y,(s.options.show.effect.length>0))}if(typeof s.options.show.solo=="object"){z=f(s.options.show.solo)}else{if(s.options.show.solo===true){z=f("div.qtip").not(s.elements.tooltip)}}if(z){z.each(function(){if(f(this).qtip("api").status.rendered===true){f(this).qtip("api").hide()}})}if(typeof s.options.show.effect.type=="function"){s.options.show.effect.type.call(s.elements.tooltip,s.options.show.effect.length);s.elements.tooltip.queue(function(){w();f(this).dequeue()})}else{switch(s.options.show.effect.type.toLowerCase()){case"fade":s.elements.tooltip.fadeIn(s.options.show.effect.length,w);break;case"slide":s.elements.tooltip.slideDown(s.options.show.effect.length,function(){w();if(s.options.position.type!=="static"){s.updatePosition(y,true)}});break;case"grow":s.elements.tooltip.show(s.options.show.effect.length,w);break;default:s.elements.tooltip.show(null,w);break}s.elements.tooltip.addClass(s.options.style.classes.active)}return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_SHOWN,"show")},hide:function(y){var x;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"hide")}else{if(s.elements.tooltip.css("display")==="none"){return s}}clearTimeout(s.timers.show);s.elements.tooltip.stop(true,false);x=s.beforeHide.call(s,y);if(x===false){return s}function w(){s.onHide.call(s,y)}s.cache.toggle=0;if(typeof s.options.hide.effect.type=="function"){s.options.hide.effect.type.call(s.elements.tooltip,s.options.hide.effect.length);s.elements.tooltip.queue(function(){w();f(this).dequeue()})}else{switch(s.options.hide.effect.type.toLowerCase()){case"fade":s.elements.tooltip.fadeOut(s.options.hide.effect.length,w);break;case"slide":s.elements.tooltip.slideUp(s.options.hide.effect.length,w);break;case"grow":s.elements.tooltip.hide(s.options.hide.effect.length,w);break;default:s.elements.tooltip.hide(null,w);break}s.elements.tooltip.removeClass(s.options.style.classes.active)}return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_HIDDEN,"hide")},updatePosition:function(w,x){var C,G,L,J,H,E,y,I,B,D,K,A,F,z;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"updatePosition")}else{if(s.options.position.type=="static"){return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.CANNOT_POSITION_STATIC,"updatePosition")}}G={position:{left:0,top:0},dimensions:{height:0,width:0},corner:s.options.position.corner.target};L={position:s.getPosition(),dimensions:s.getDimensions(),corner:s.options.position.corner.tooltip};if(s.options.position.target!=="mouse"){if(s.options.position.target.get(0).nodeName.toLowerCase()=="area"){J=s.options.position.target.attr("coords").split(",");for(C=0;C<J.length;C++){J[C]=parseInt(J[C])}H=s.options.position.target.parent("map").attr("name");E=f('img[usemap="#'+H+'"]:first').offset();G.position={left:Math.floor(E.left+J[0]),top:Math.floor(E.top+J[1])};switch(s.options.position.target.attr("shape").toLowerCase()){case"rect":G.dimensions={width:Math.ceil(Math.abs(J[2]-J[0])),height:Math.ceil(Math.abs(J[3]-J[1]))};break;case"circle":G.dimensions={width:J[2]+1,height:J[2]+1};break;case"poly":G.dimensions={width:J[0],height:J[1]};for(C=0;C<J.length;C++){if(C%2==0){if(J[C]>G.dimensions.width){G.dimensions.width=J[C]}if(J[C]<J[0]){G.position.left=Math.floor(E.left+J[C])}}else{if(J[C]>G.dimensions.height){G.dimensions.height=J[C]}if(J[C]<J[1]){G.position.top=Math.floor(E.top+J[C])}}}G.dimensions.width=G.dimensions.width-(G.position.left-E.left);G.dimensions.height=G.dimensions.height-(G.position.top-E.top);break;default:return f.fn.qtip.log.error.call(s,4,f.fn.qtip.constants.INVALID_AREA_SHAPE,"updatePosition");break}G.dimensions.width-=2;G.dimensions.height-=2}else{if(s.options.position.target.add(document.body).length===1){G.position={left:f(document).scrollLeft(),top:f(document).scrollTop()};G.dimensions={height:f(window).height(),width:f(window).width()}}else{if(typeof s.options.position.target.attr("qtip")!=="undefined"){G.position=s.options.position.target.qtip("api").cache.position}else{G.position=s.options.position.target.offset()}G.dimensions={height:s.options.position.target.outerHeight(),width:s.options.position.target.outerWidth()}}}y=f.extend({},G.position);if(G.corner.search(/right/i)!==-1){y.left+=G.dimensions.width}if(G.corner.search(/bottom/i)!==-1){y.top+=G.dimensions.height}if(G.corner.search(/((top|bottom)Middle)|center/)!==-1){y.left+=(G.dimensions.width/2)}if(G.corner.search(/((left|right)Middle)|center/)!==-1){y.top+=(G.dimensions.height/2)}}else{G.position=y={left:s.cache.mouse.x,top:s.cache.mouse.y};G.dimensions={height:1,width:1}}if(L.corner.search(/right/i)!==-1){y.left-=L.dimensions.width}if(L.corner.search(/bottom/i)!==-1){y.top-=L.dimensions.height}if(L.corner.search(/((top|bottom)Middle)|center/)!==-1){y.left-=(L.dimensions.width/2)}if(L.corner.search(/((left|right)Middle)|center/)!==-1){y.top-=(L.dimensions.height/2)}I=(f.browser.msie)?1:0;B=(f.browser.msie&&parseInt(f.browser.version.charAt(0))===6)?1:0;if(s.options.style.border.radius>0){if(L.corner.search(/Left/)!==-1){y.left-=s.options.style.border.radius}else{if(L.corner.search(/Right/)!==-1){y.left+=s.options.style.border.radius}}if(L.corner.search(/Top/)!==-1){y.top-=s.options.style.border.radius}else{if(L.corner.search(/Bottom/)!==-1){y.top+=s.options.style.border.radius}}}if(I){if(L.corner.search(/top/)!==-1){y.top-=I}else{if(L.corner.search(/bottom/)!==-1){y.top+=I}}if(L.corner.search(/left/)!==-1){y.left-=I}else{if(L.corner.search(/right/)!==-1){y.left+=I}}if(L.corner.search(/leftMiddle|rightMiddle/)!==-1){y.top-=1}}if(s.options.position.adjust.screen===true){y=o.call(s,y,G,L)}if(s.options.position.target==="mouse"&&s.options.position.adjust.mouse===true){if(s.options.position.adjust.screen===true&&s.elements.tip){K=s.elements.tip.attr("rel")}else{K=s.options.position.corner.tooltip}y.left+=(K.search(/right/i)!==-1)?-6:6;y.top+=(K.search(/bottom/i)!==-1)?-6:6}if(!s.elements.bgiframe&&f.browser.msie&&parseInt(f.browser.version.charAt(0))==6){f("select, object").each(function(){A=f(this).offset();A.bottom=A.top+f(this).height();A.right=A.left+f(this).width();if(y.top+L.dimensions.height>=A.top&&y.left+L.dimensions.width>=A.left){k.call(s)}})}y.left+=s.options.position.adjust.x;y.top+=s.options.position.adjust.y;F=s.getPosition();if(y.left!=F.left||y.top!=F.top){z=s.beforePositionUpdate.call(s,w);if(z===false){return s}s.cache.position=y;if(x===true){s.status.animated=true;s.elements.tooltip.animate(y,200,"swing",function(){s.status.animated=false})}else{s.elements.tooltip.css(y)}s.onPositionUpdate.call(s,w);if(typeof w!=="undefined"&&w.type&&w.type!=="mousemove"){f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_POSITION_UPDATED,"updatePosition")}}return s},updateWidth:function(w){var x;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"updateWidth")}else{if(w&&typeof w!=="number"){return f.fn.qtip.log.error.call(s,2,"newWidth must be of type number","updateWidth")}}x=s.elements.contentWrapper.siblings().add(s.elements.tip).add(s.elements.button);if(!w){if(typeof s.options.style.width.value=="number"){w=s.options.style.width.value}else{s.elements.tooltip.css({width:"auto"});x.hide();if(f.browser.msie){s.elements.wrapper.add(s.elements.contentWrapper.children()).css({zoom:"normal"})}w=s.getDimensions().width+1;if(!s.options.style.width.value){if(w>s.options.style.width.max){w=s.options.style.width.max}if(w<s.options.style.width.min){w=s.options.style.width.min}}}}if(w%2!==0){w-=1}s.elements.tooltip.width(w);x.show();if(s.options.style.border.radius){s.elements.tooltip.find(".qtip-betweenCorners").each(function(y){f(this).width(w-(s.options.style.border.radius*2))})}if(f.browser.msie){s.elements.wrapper.add(s.elements.contentWrapper.children()).css({zoom:"1"});s.elements.wrapper.width(w);if(s.elements.bgiframe){s.elements.bgiframe.width(w).height(s.getDimensions.height)}}return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_WIDTH_UPDATED,"updateWidth")},updateStyle:function(w){var z,A,x,y,B;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"updateStyle")}else{if(typeof w!=="string"||!f.fn.qtip.styles[w]){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.STYLE_NOT_DEFINED,"updateStyle")}}s.options.style=a.call(s,f.fn.qtip.styles[w],s.options.user.style);s.elements.content.css(q(s.options.style));if(s.options.content.title.text!==false){s.elements.title.css(q(s.options.style.title,true))}s.elements.contentWrapper.css({borderColor:s.options.style.border.color});if(s.options.style.tip.corner!==false){if(f("<canvas>").get(0).getContext){z=s.elements.tooltip.find(".qtip-tip canvas:first");x=z.get(0).getContext("2d");x.clearRect(0,0,300,300);y=z.parent("div[rel]:first").attr("rel");B=b(y,s.options.style.tip.size.width,s.options.style.tip.size.height);h.call(s,z,B,s.options.style.tip.color||s.options.style.border.color)}else{if(f.browser.msie){z=s.elements.tooltip.find('.qtip-tip [nodeName="shape"]');z.attr("fillcolor",s.options.style.tip.color||s.options.style.border.color)}}}if(s.options.style.border.radius>0){s.elements.tooltip.find(".qtip-betweenCorners").css({backgroundColor:s.options.style.border.color});if(f("<canvas>").get(0).getContext){A=g(s.options.style.border.radius);s.elements.tooltip.find(".qtip-wrapper canvas").each(function(){x=f(this).get(0).getContext("2d");x.clearRect(0,0,300,300);y=f(this).parent("div[rel]:first").attr("rel");r.call(s,f(this),A[y],s.options.style.border.radius,s.options.style.border.color)})}else{if(f.browser.msie){s.elements.tooltip.find('.qtip-wrapper [nodeName="arc"]').each(function(){f(this).attr("fillcolor",s.options.style.border.color)})}}}return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_STYLE_UPDATED,"updateStyle")},updateContent:function(A,y){var z,x,w;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"updateContent")}else{if(!A){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.NO_CONTENT_PROVIDED,"updateContent")}}z=s.beforeContentUpdate.call(s,A);if(typeof z=="string"){A=z}else{if(z===false){return}}if(f.browser.msie){s.elements.contentWrapper.children().css({zoom:"normal"})}if(A.jquery&&A.length>0){A.clone(true).appendTo(s.elements.content).show()}else{s.elements.content.html(A)}x=s.elements.content.find("img[complete=false]");if(x.length>0){w=0;x.each(function(C){f('<img src="'+f(this).attr("src")+'" />').load(function(){if(++w==x.length){B()}})})}else{B()}function B(){s.updateWidth();if(y!==false){if(s.options.position.type!=="static"){s.updatePosition(s.elements.tooltip.is(":visible"),true)}if(s.options.style.tip.corner!==false){n.call(s)}}}s.onContentUpdate.call(s);return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_CONTENT_UPDATED,"loadContent")},loadContent:function(w,z,A){var y;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"loadContent")}y=s.beforeContentLoad.call(s);if(y===false){return s}if(A=="post"){f.post(w,z,x)}else{f.get(w,z,x)}function x(B){s.onContentLoad.call(s);f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_CONTENT_LOADED,"loadContent");s.updateContent(B)}return s},updateTitle:function(w){if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"updateTitle")}else{if(!w){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.NO_CONTENT_PROVIDED,"updateTitle")}}returned=s.beforeTitleUpdate.call(s);if(returned===false){return s}if(s.elements.button){s.elements.button=s.elements.button.clone(true)}s.elements.title.html(w);if(s.elements.button){s.elements.title.prepend(s.elements.button)}s.onTitleUpdate.call(s);return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_TITLE_UPDATED,"updateTitle")},focus:function(A){var y,x,w,z;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"focus")}else{if(s.options.position.type=="static"){return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.CANNOT_FOCUS_STATIC,"focus")}}y=parseInt(s.elements.tooltip.css("z-index"));x=6000+f("div.qtip[qtip]").length-1;if(!s.status.focused&&y!==x){z=s.beforeFocus.call(s,A);if(z===false){return s}f("div.qtip[qtip]").not(s.elements.tooltip).each(function(){if(f(this).qtip("api").status.rendered===true){w=parseInt(f(this).css("z-index"));if(typeof w=="number"&&w>-1){f(this).css({zIndex:parseInt(f(this).css("z-index"))-1})}f(this).qtip("api").status.focused=false}});s.elements.tooltip.css({zIndex:x});s.status.focused=true;s.onFocus.call(s,A);f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_FOCUSED,"focus")}return s},disable:function(w){if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"disable")}if(w){if(!s.status.disabled){s.status.disabled=true;f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_DISABLED,"disable")}else{f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.TOOLTIP_ALREADY_DISABLED,"disable")}}else{if(s.status.disabled){s.status.disabled=false;f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_ENABLED,"disable")}else{f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.TOOLTIP_ALREADY_ENABLED,"disable")}}return s},destroy:function(){var w,x,y;x=s.beforeDestroy.call(s);if(x===false){return s}if(s.status.rendered){s.options.show.when.target.unbind("mousemove.qtip",s.updatePosition);s.options.show.when.target.unbind("mouseout.qtip",s.hide);s.options.show.when.target.unbind(s.options.show.when.event+".qtip");s.options.hide.when.target.unbind(s.options.hide.when.event+".qtip");s.elements.tooltip.unbind(s.options.hide.when.event+".qtip");s.elements.tooltip.unbind("mouseover.qtip",s.focus);s.elements.tooltip.remove()}else{s.options.show.when.target.unbind(s.options.show.when.event+".qtip-create")}if(typeof s.elements.target.data("qtip")=="object"){y=s.elements.target.data("qtip").interfaces;if(typeof y=="object"&&y.length>0){for(w=0;w<y.length-1;w++){if(y[w].id==s.id){y.splice(w,1)}}}}delete f.fn.qtip.interfaces[s.id];if(typeof y=="object"&&y.length>0){s.elements.target.data("qtip").current=y.length-1}else{s.elements.target.removeData("qtip")}s.onDestroy.call(s);f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_DESTROYED,"destroy");return s.elements.target},getPosition:function(){var w,x;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"getPosition")}w=(s.elements.tooltip.css("display")!=="none")?false:true;if(w){s.elements.tooltip.css({visiblity:"hidden"}).show()}x=s.elements.tooltip.offset();if(w){s.elements.tooltip.css({visiblity:"visible"}).hide()}return x},getDimensions:function(){var w,x;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"getDimensions")}w=(!s.elements.tooltip.is(":visible"))?true:false;if(w){s.elements.tooltip.css({visiblity:"hidden"}).show()}x={height:s.elements.tooltip.outerHeight(),width:s.elements.tooltip.outerWidth()};if(w){s.elements.tooltip.css({visiblity:"visible"}).hide()}return x}})}function p(){var s,w,u,t,v,y,x;s=this;s.beforeRender.call(s);s.status.rendered=true;s.elements.tooltip='<div qtip="'+s.id+'" class="qtip '+(s.options.style.classes.tooltip||s.options.style)+'"style="display:none; -moz-border-radius:0; -webkit-border-radius:0; border-radius:0;position:'+s.options.position.type+';">  <div class="qtip-wrapper" style="position:relative; overflow:hidden; text-align:left;">    <div class="qtip-contentWrapper" style="overflow:hidden;">       <div class="qtip-content '+s.options.style.classes.content+'"></div></div></div></div>';s.elements.tooltip=f(s.elements.tooltip);s.elements.tooltip.appendTo(s.options.position.container);s.elements.tooltip.data("qtip",{current:0,interfaces:[s]});s.elements.wrapper=s.elements.tooltip.children("div:first");s.elements.contentWrapper=s.elements.wrapper.children("div:first").css({background:s.options.style.background});s.elements.content=s.elements.contentWrapper.children("div:first").css(q(s.options.style));if(f.browser.msie){s.elements.wrapper.add(s.elements.content).css({zoom:1})}if(s.options.hide.when.event=="unfocus"){s.elements.tooltip.attr("unfocus",true)}if(typeof s.options.style.width.value=="number"){s.updateWidth()}if(f("<canvas>").get(0).getContext||f.browser.msie){if(s.options.style.border.radius>0){m.call(s)}else{s.elements.contentWrapper.css({border:s.options.style.border.width+"px solid "+s.options.style.border.color})}if(s.options.style.tip.corner!==false){e.call(s)}}else{s.elements.contentWrapper.css({border:s.options.style.border.width+"px solid "+s.options.style.border.color});s.options.style.border.radius=0;s.options.style.tip.corner=false;f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.CANVAS_VML_NOT_SUPPORTED,"render")}if((typeof s.options.content.text=="string"&&s.options.content.text.length>0)||(s.options.content.text.jquery&&s.options.content.text.length>0)){u=s.options.content.text}else{if(typeof s.elements.target.attr("title")=="string"&&s.elements.target.attr("title").length>0){u=s.elements.target.attr("title").replace("\\n","<br />");s.elements.target.attr("title","")}else{if(typeof s.elements.target.attr("alt")=="string"&&s.elements.target.attr("alt").length>0){u=s.elements.target.attr("alt").replace("\\n","<br />");s.elements.target.attr("alt","")}else{u=" ";f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.NO_VALID_CONTENT,"render")}}}if(s.options.content.title.text!==false){j.call(s)}s.updateContent(u);l.call(s);if(s.options.show.ready===true){s.show()}if(s.options.content.url!==false){t=s.options.content.url;v=s.options.content.data;y=s.options.content.method||"get";s.loadContent(t,v,y)}s.onRender.call(s);f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_RENDERED,"render")}function m(){var F,z,t,B,x,E,u,G,D,y,w,C,A,s,v;F=this;F.elements.wrapper.find(".qtip-borderBottom, .qtip-borderTop").remove();t=F.options.style.border.width;B=F.options.style.border.radius;x=F.options.style.border.color||F.options.style.tip.color;E=g(B);u={};for(z in E){u[z]='<div rel="'+z+'" style="'+((z.search(/Left/)!==-1)?"left":"right")+":0; position:absolute; height:"+B+"px; width:"+B+'px; overflow:hidden; line-height:0.1px; font-size:1px">';if(f("<canvas>").get(0).getContext){u[z]+='<canvas height="'+B+'" width="'+B+'" style="vertical-align: top"></canvas>'}else{if(f.browser.msie){G=B*2+3;u[z]+='<v:arc stroked="false" fillcolor="'+x+'" startangle="'+E[z][0]+'" endangle="'+E[z][1]+'" style="width:'+G+"px; height:"+G+"px; margin-top:"+((z.search(/bottom/)!==-1)?-2:-1)+"px; margin-left:"+((z.search(/Right/)!==-1)?E[z][2]-3.5:-1)+'px; vertical-align:top; display:inline-block; behavior:url(#default#VML)"></v:arc>'}}u[z]+="</div>"}D=F.getDimensions().width-(Math.max(t,B)*2);y='<div class="qtip-betweenCorners" style="height:'+B+"px; width:"+D+"px; overflow:hidden; background-color:"+x+'; line-height:0.1px; font-size:1px;">';w='<div class="qtip-borderTop" dir="ltr" style="height:'+B+"px; margin-left:"+B+'px; line-height:0.1px; font-size:1px; padding:0;">'+u.topLeft+u.topRight+y;F.elements.wrapper.prepend(w);C='<div class="qtip-borderBottom" dir="ltr" style="height:'+B+"px; margin-left:"+B+'px; line-height:0.1px; font-size:1px; padding:0;">'+u.bottomLeft+u.bottomRight+y;F.elements.wrapper.append(C);if(f("<canvas>").get(0).getContext){F.elements.wrapper.find("canvas").each(function(){A=E[f(this).parent("[rel]:first").attr("rel")];r.call(F,f(this),A,B,x)})}else{if(f.browser.msie){F.elements.tooltip.append('<v:image style="behavior:url(#default#VML);"></v:image>')}}s=Math.max(B,(B+(t-B)));v=Math.max(t-B,0);F.elements.contentWrapper.css({border:"0px solid "+x,borderWidth:v+"px "+s+"px"})}function r(u,w,s,t){var v=u.get(0).getContext("2d");v.fillStyle=t;v.beginPath();v.arc(w[0],w[1],s,0,Math.PI*2,false);v.fill()}function e(v){var t,s,x,u,w;t=this;if(t.elements.tip!==null){t.elements.tip.remove()}s=t.options.style.tip.color||t.options.style.border.color;if(t.options.style.tip.corner===false){return}else{if(!v){v=t.options.style.tip.corner}}x=b(v,t.options.style.tip.size.width,t.options.style.tip.size.height);t.elements.tip='<div class="'+t.options.style.classes.tip+'" dir="ltr" rel="'+v+'" style="position:absolute; height:'+t.options.style.tip.size.height+"px; width:"+t.options.style.tip.size.width+'px; margin:0 auto; line-height:0.1px; font-size:1px;">';if(f("<canvas>").get(0).getContext){t.elements.tip+='<canvas height="'+t.options.style.tip.size.height+'" width="'+t.options.style.tip.size.width+'"></canvas>'}else{if(f.browser.msie){u=t.options.style.tip.size.width+","+t.options.style.tip.size.height;w="m"+x[0][0]+","+x[0][1];w+=" l"+x[1][0]+","+x[1][1];w+=" "+x[2][0]+","+x[2][1];w+=" xe";t.elements.tip+='<v:shape fillcolor="'+s+'" stroked="false" filled="true" path="'+w+'" coordsize="'+u+'" style="width:'+t.options.style.tip.size.width+"px; height:"+t.options.style.tip.size.height+"px; line-height:0.1px; display:inline-block; behavior:url(#default#VML); vertical-align:"+((v.search(/top/)!==-1)?"bottom":"top")+'"></v:shape>';t.elements.tip+='<v:image style="behavior:url(#default#VML);"></v:image>';t.elements.contentWrapper.css("position","relative")}}t.elements.tooltip.prepend(t.elements.tip+"</div>");t.elements.tip=t.elements.tooltip.find("."+t.options.style.classes.tip).eq(0);if(f("<canvas>").get(0).getContext){h.call(t,t.elements.tip.find("canvas:first"),x,s)}if(v.search(/top/)!==-1&&f.browser.msie&&parseInt(f.browser.version.charAt(0))===6){t.elements.tip.css({marginTop:-4})}n.call(t,v)}function h(t,v,s){var u=t.get(0).getContext("2d");u.fillStyle=s;u.beginPath();u.moveTo(v[0][0],v[0][1]);u.lineTo(v[1][0],v[1][1]);u.lineTo(v[2][0],v[2][1]);u.fill()}function n(u){var t,w,s,x,v;t=this;if(t.options.style.tip.corner===false||!t.elements.tip){return}if(!u){u=t.elements.tip.attr("rel")}w=positionAdjust=(f.browser.msie)?1:0;t.elements.tip.css(u.match(/left|right|top|bottom/)[0],0);if(u.search(/top|bottom/)!==-1){if(f.browser.msie){if(parseInt(f.browser.version.charAt(0))===6){positionAdjust=(u.search(/top/)!==-1)?-3:1}else{positionAdjust=(u.search(/top/)!==-1)?1:2}}if(u.search(/Middle/)!==-1){t.elements.tip.css({left:"50%",marginLeft:-(t.options.style.tip.size.width/2)})}else{if(u.search(/Left/)!==-1){t.elements.tip.css({left:t.options.style.border.radius-w})}else{if(u.search(/Right/)!==-1){t.elements.tip.css({right:t.options.style.border.radius+w})}}}if(u.search(/top/)!==-1){t.elements.tip.css({top:-positionAdjust})}else{t.elements.tip.css({bottom:positionAdjust})}}else{if(u.search(/left|right/)!==-1){if(f.browser.msie){positionAdjust=(parseInt(f.browser.version.charAt(0))===6)?1:((u.search(/left/)!==-1)?1:2)}if(u.search(/Middle/)!==-1){t.elements.tip.css({top:"50%",marginTop:-(t.options.style.tip.size.height/2)})}else{if(u.search(/Top/)!==-1){t.elements.tip.css({top:t.options.style.border.radius-w})}else{if(u.search(/Bottom/)!==-1){t.elements.tip.css({bottom:t.options.style.border.radius+w})}}}if(u.search(/left/)!==-1){t.elements.tip.css({left:-positionAdjust})}else{t.elements.tip.css({right:positionAdjust})}}}s="padding-"+u.match(/left|right|top|bottom/)[0];x=t.options.style.tip.size[(s.search(/left|right/)!==-1)?"width":"height"];t.elements.tooltip.css("padding",0);t.elements.tooltip.css(s,x);if(f.browser.msie&&parseInt(f.browser.version.charAt(0))==6){v=parseInt(t.elements.tip.css("margin-top"))||0;v+=parseInt(t.elements.content.css("margin-top"))||0;t.elements.tip.css({marginTop:v})}}function j(){var s=this;if(s.elements.title!==null){s.elements.title.remove()}s.elements.title=f('<div class="'+s.options.style.classes.title+'">').css(q(s.options.style.title,true)).css({zoom:(f.browser.msie)?1:0}).prependTo(s.elements.contentWrapper);if(s.options.content.title.text){s.updateTitle.call(s,s.options.content.title.text)}if(s.options.content.title.button!==false&&typeof s.options.content.title.button=="string"){s.elements.button=f('<a class="'+s.options.style.classes.button+'" style="float:right; position: relative"></a>').css(q(s.options.style.button,true)).html(s.options.content.title.button).prependTo(s.elements.title).click(function(t){if(!s.status.disabled){s.hide(t)}})}}function l(){var t,v,u,s;t=this;v=t.options.show.when.target;u=t.options.hide.when.target;if(t.options.hide.fixed){u=u.add(t.elements.tooltip)}if(t.options.hide.when.event=="inactive"){s=["click","dblclick","mousedown","mouseup","mousemove","mouseout","mouseenter","mouseleave","mouseover"];function y(z){if(t.status.disabled===true){return}clearTimeout(t.timers.inactive);t.timers.inactive=setTimeout(function(){f(s).each(function(){u.unbind(this+".qtip-inactive");t.elements.content.unbind(this+".qtip-inactive")});t.hide(z)},t.options.hide.delay)}}else{if(t.options.hide.fixed===true){t.elements.tooltip.bind("mouseover.qtip",function(){if(t.status.disabled===true){return}clearTimeout(t.timers.hide)})}}function x(z){if(t.status.disabled===true){return}if(t.options.hide.when.event=="inactive"){f(s).each(function(){u.bind(this+".qtip-inactive",y);t.elements.content.bind(this+".qtip-inactive",y)});y()}clearTimeout(t.timers.show);clearTimeout(t.timers.hide);t.timers.show=setTimeout(function(){t.show(z)},t.options.show.delay)}function w(z){if(t.status.disabled===true){return}if(t.options.hide.fixed===true&&t.options.hide.when.event.search(/mouse(out|leave)/i)!==-1&&f(z.relatedTarget).parents("div.qtip[qtip]").length>0){z.stopPropagation();z.preventDefault();clearTimeout(t.timers.hide);return false}clearTimeout(t.timers.show);clearTimeout(t.timers.hide);t.elements.tooltip.stop(true,true);t.timers.hide=setTimeout(function(){t.hide(z)},t.options.hide.delay)}if((t.options.show.when.target.add(t.options.hide.when.target).length===1&&t.options.show.when.event==t.options.hide.when.event&&t.options.hide.when.event!=="inactive")||t.options.hide.when.event=="unfocus"){t.cache.toggle=0;v.bind(t.options.show.when.event+".qtip",function(z){if(t.cache.toggle==0){x(z)}else{w(z)}})}else{v.bind(t.options.show.when.event+".qtip",x);if(t.options.hide.when.event!=="inactive"){u.bind(t.options.hide.when.event+".qtip",w)}}if(t.options.position.type.search(/(fixed|absolute)/)!==-1){t.elements.tooltip.bind("mouseover.qtip",t.focus)}if(t.options.position.target==="mouse"&&t.options.position.type!=="static"){v.bind("mousemove.qtip",function(z){t.cache.mouse={x:z.pageX,y:z.pageY};if(t.status.disabled===false&&t.options.position.adjust.mouse===true&&t.options.position.type!=="static"&&t.elements.tooltip.css("display")!=="none"){t.updatePosition(z)}})}}function o(u,v,A){var z,s,x,y,t,w;z=this;if(A.corner=="center"){return v.position}s=f.extend({},u);y={x:false,y:false};t={left:(s.left<f.fn.qtip.cache.screen.scroll.left),right:(s.left+A.dimensions.width+2>=f.fn.qtip.cache.screen.width+f.fn.qtip.cache.screen.scroll.left),top:(s.top<f.fn.qtip.cache.screen.scroll.top),bottom:(s.top+A.dimensions.height+2>=f.fn.qtip.cache.screen.height+f.fn.qtip.cache.screen.scroll.top)};x={left:(t.left&&(A.corner.search(/right/i)!=-1||(A.corner.search(/right/i)==-1&&!t.right))),right:(t.right&&(A.corner.search(/left/i)!=-1||(A.corner.search(/left/i)==-1&&!t.left))),top:(t.top&&A.corner.search(/top/i)==-1),bottom:(t.bottom&&A.corner.search(/bottom/i)==-1)};if(x.left){if(z.options.position.target!=="mouse"){s.left=v.position.left+v.dimensions.width}else{s.left=z.cache.mouse.x}y.x="Left"}else{if(x.right){if(z.options.position.target!=="mouse"){s.left=v.position.left-A.dimensions.width}else{s.left=z.cache.mouse.x-A.dimensions.width}y.x="Right"}}if(x.top){if(z.options.position.target!=="mouse"){s.top=v.position.top+v.dimensions.height}else{s.top=z.cache.mouse.y}y.y="top"}else{if(x.bottom){if(z.options.position.target!=="mouse"){s.top=v.position.top-A.dimensions.height}else{s.top=z.cache.mouse.y-A.dimensions.height}y.y="bottom"}}if(s.left<0){s.left=u.left;y.x=false}if(s.top<0){s.top=u.top;y.y=false}if(z.options.style.tip.corner!==false){s.corner=new String(A.corner);if(y.x!==false){s.corner=s.corner.replace(/Left|Right|Middle/,y.x)}if(y.y!==false){s.corner=s.corner.replace(/top|bottom/,y.y)}if(s.corner!==z.elements.tip.attr("rel")){e.call(z,s.corner)}}return s}function q(u,t){var v,s;v=f.extend(true,{},u);for(s in v){if(t===true&&s.search(/(tip|classes)/i)!==-1){delete v[s]}else{if(!t&&s.search(/(width|border|tip|title|classes|user)/i)!==-1){delete v[s]}}}return v}function c(s){if(typeof s.tip!=="object"){s.tip={corner:s.tip}}if(typeof s.tip.size!=="object"){s.tip.size={width:s.tip.size,height:s.tip.size}}if(typeof s.border!=="object"){s.border={width:s.border}}if(typeof s.width!=="object"){s.width={value:s.width}}if(typeof s.width.max=="string"){s.width.max=parseInt(s.width.max.replace(/([0-9]+)/i,"$1"))}if(typeof s.width.min=="string"){s.width.min=parseInt(s.width.min.replace(/([0-9]+)/i,"$1"))}if(typeof s.tip.size.x=="number"){s.tip.size.width=s.tip.size.x;delete s.tip.size.x}if(typeof s.tip.size.y=="number"){s.tip.size.height=s.tip.size.y;delete s.tip.size.y}return s}function a(){var s,t,u,x,v,w;s=this;u=[true,{}];for(t=0;t<arguments.length;t++){u.push(arguments[t])}x=[f.extend.apply(f,u)];while(typeof x[0].name=="string"){x.unshift(c(f.fn.qtip.styles[x[0].name]))}x.unshift(true,{classes:{tooltip:"qtip-"+(arguments[0].name||"defaults")}},f.fn.qtip.styles.defaults);v=f.extend.apply(f,x);w=(f.browser.msie)?1:0;v.tip.size.width+=w;v.tip.size.height+=w;if(v.tip.size.width%2>0){v.tip.size.width+=1}if(v.tip.size.height%2>0){v.tip.size.height+=1}if(v.tip.corner===true){v.tip.corner=(s.options.position.corner.tooltip==="center")?false:s.options.position.corner.tooltip}return v}function b(v,u,t){var s={bottomRight:[[0,0],[u,t],[u,0]],bottomLeft:[[0,0],[u,0],[0,t]],topRight:[[0,t],[u,0],[u,t]],topLeft:[[0,0],[0,t],[u,t]],topMiddle:[[0,t],[u/2,0],[u,t]],bottomMiddle:[[0,0],[u,0],[u/2,t]],rightMiddle:[[0,0],[u,t/2],[0,t]],leftMiddle:[[u,0],[u,t],[0,t/2]]};s.leftTop=s.bottomRight;s.rightTop=s.bottomLeft;s.leftBottom=s.topRight;s.rightBottom=s.topLeft;return s[v]}function g(s){var t;if(f("<canvas>").get(0).getContext){t={topLeft:[s,s],topRight:[0,s],bottomLeft:[s,0],bottomRight:[0,0]}}else{if(f.browser.msie){t={topLeft:[-90,90,0],topRight:[-90,90,-s],bottomLeft:[90,270,0],bottomRight:[90,270,-s]}}}return t}function k(){var s,t,u;s=this;u=s.getDimensions();t='<iframe class="qtip-bgiframe" frameborder="0" tabindex="-1" src="javascript:false" style="display:block; position:absolute; z-index:-1; filter:alpha(opacity=\'0\'); border: 1px solid red; height:'+u.height+"px; width:"+u.width+'px" />';s.elements.bgiframe=s.elements.wrapper.prepend(t).children(".qtip-bgiframe:first")}f(document).ready(function(){f.fn.qtip.cache={screen:{scroll:{left:f(window).scrollLeft(),top:f(window).scrollTop()},width:f(window).width(),height:f(window).height()}};var s;f(window).bind("resize scroll",function(t){clearTimeout(s);s=setTimeout(function(){if(t.type==="scroll"){f.fn.qtip.cache.screen.scroll={left:f(window).scrollLeft(),top:f(window).scrollTop()}}else{f.fn.qtip.cache.screen.width=f(window).width();f.fn.qtip.cache.screen.height=f(window).height()}for(i=0;i<f.fn.qtip.interfaces.length;i++){var u=f.fn.qtip.interfaces[i];if(u.status.rendered===true&&(u.options.position.type!=="static"||u.options.position.adjust.scroll&&t.type==="scroll"||u.options.position.adjust.resize&&t.type==="resize")){u.updatePosition(t,true)}}},100)});f(document).bind("mousedown.qtip",function(t){if(f(t.target).parents("div.qtip").length===0){f(".qtip[unfocus]").each(function(){var u=f(this).qtip("api");if(f(this).is(":visible")&&!u.status.disabled&&f(t.target).add(u.elements.target).length>1){u.hide(t)}})}})});f.fn.qtip.interfaces=[];f.fn.qtip.log={error:function(){return this}};f.fn.qtip.constants={};f.fn.qtip.defaults={content:{prerender:false,text:false,url:false,data:null,title:{text:false,button:false}},position:{target:false,corner:{target:"bottomRight",tooltip:"topLeft"},adjust:{x:0,y:0,mouse:true,screen:false,scroll:true,resize:true},type:"absolute",container:false},show:{when:{target:false,event:"mouseover"},effect:{type:"fade",length:100},delay:140,solo:false,ready:false},hide:{when:{target:false,event:"mouseout"},effect:{type:"fade",length:100},delay:0,fixed:false},api:{beforeRender:function(){},onRender:function(){},beforePositionUpdate:function(){},onPositionUpdate:function(){},beforeShow:function(){},onShow:function(){},beforeHide:function(){},onHide:function(){},beforeContentUpdate:function(){},onContentUpdate:function(){},beforeContentLoad:function(){},onContentLoad:function(){},beforeTitleUpdate:function(){},onTitleUpdate:function(){},beforeDestroy:function(){},onDestroy:function(){},beforeFocus:function(){},onFocus:function(){}}};f.fn.qtip.styles={defaults:{background:"white",color:"#111",overflow:"hidden",textAlign:"left",width:{min:0,max:250},padding:"5px 9px",border:{width:1,radius:0,color:"#d3d3d3"},tip:{corner:false,color:false,size:{width:13,height:13},opacity:1},title:{background:"#e1e1e1",fontWeight:"bold",padding:"7px 12px"},button:{cursor:"pointer"},classes:{target:"",tip:"qtip-tip",title:"qtip-title",button:"qtip-button",content:"qtip-content",active:"qtip-active"}},cream:{border:{width:3,radius:0,color:"#F9E98E"},title:{background:"#F0DE7D",color:"#A27D35"},background:"#FBF7AA",color:"#A27D35",classes:{tooltip:"qtip-cream"}},light:{border:{width:3,radius:0,color:"#E2E2E2"},title:{background:"#f1f1f1",color:"#454545"},background:"white",color:"#454545",classes:{tooltip:"qtip-light"}},dark:{border:{width:3,radius:0,color:"#303030"},title:{background:"#404040",color:"#f3f3f3"},background:"#505050",color:"#f3f3f3",classes:{tooltip:"qtip-dark"}},red:{border:{width:3,radius:0,color:"#CE6F6F"},title:{background:"#f28279",color:"#9C2F2F"},background:"#F79992",color:"#9C2F2F",classes:{tooltip:"qtip-red"}},green:{border:{width:3,radius:0,color:"#A9DB66"},title:{background:"#b9db8c",color:"#58792E"},background:"#CDE6AC",color:"#58792E",classes:{tooltip:"qtip-green"}},blue:{border:{width:3,radius:0,color:"#ADD9ED"},title:{background:"#D0E9F5",color:"#5E99BD"},background:"#E5F6FE",color:"#4D9FBF",classes:{tooltip:"qtip-blue"}}}})(jQuery);

/**
 * jQuery Form Plugin
 * version: 2.28 (10-MAY-2009)
 * @requires jQuery v1.2.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function(B){B.fn.ajaxSubmit=function(O){if(!this.length){A("ajaxSubmit: skipping submit process - no element selected");return this}if(typeof O=="function"){O={success:O}}var E=B.trim(this.attr("action"));if(E){E=(E.match(/^([^#]+)/)||[])[1]}E=E||window.location.href||"";O=B.extend({url:E,type:this.attr("method")||"GET"},O||{});var Q={};this.trigger("form-pre-serialize",[this,O,Q]);if(Q.veto){A("ajaxSubmit: submit vetoed via form-pre-serialize trigger");return this}if(O.beforeSerialize&&O.beforeSerialize(this,O)===false){A("ajaxSubmit: submit aborted via beforeSerialize callback");return this}var K=this.formToArray(O.semantic);if(O.data){O.extraData=O.data;for(var F in O.data){if(O.data[F] instanceof Array){for(var G in O.data[F]){K.push({name:F,value:O.data[F][G]})}}else{K.push({name:F,value:O.data[F]})}}}if(O.beforeSubmit&&O.beforeSubmit(K,this,O)===false){A("ajaxSubmit: submit aborted via beforeSubmit callback");return this}this.trigger("form-submit-validate",[K,this,O,Q]);if(Q.veto){A("ajaxSubmit: submit vetoed via form-submit-validate trigger");return this}var D=B.param(K);if(O.type.toUpperCase()=="GET"){O.url+=(O.url.indexOf("?")>=0?"&":"?")+D;O.data=null}else{O.data=D}var P=this,J=[];if(O.resetForm){J.push(function(){P.resetForm()})}if(O.clearForm){J.push(function(){P.clearForm()})}if(!O.dataType&&O.target){var M=O.success||function(){};J.push(function(R){B(O.target).html(R).each(M,arguments)})}else{if(O.success){J.push(O.success)}}O.success=function(U,S){for(var T=0,R=J.length;T<R;T++){J[T].apply(O,[U,S,P])}};var C=B("input:file",this).fieldValue();var N=false;for(var I=0;I<C.length;I++){if(C[I]){N=true}}var H=false;if(O.iframe||N||H){if(O.closeKeepAlive){B.get(O.closeKeepAlive,L)}else{L()}}else{B.ajax(O)}this.trigger("form-submit-notify",[this,O]);return this;function L(){var V=P[0];if(B(":input[name=submit]",V).length){alert('Error: Form elements must not be named "submit".');return }var T=B.extend({},B.ajaxSettings,O);var f=B.extend(true,{},B.extend(true,{},B.ajaxSettings),T);var U="jqFormIO"+(new Date().getTime());var b=B('<iframe id="'+U+'" name="'+U+'" src="about:blank" />');var d=b[0];b.css({position:"absolute",top:"-1000px",left:"-1000px"});var e={aborted:0,responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(){this.aborted=1;b.attr("src","about:blank")}};var c=T.global;if(c&&!B.active++){B.event.trigger("ajaxStart")}if(c){B.event.trigger("ajaxSend",[e,T])}if(f.beforeSend&&f.beforeSend(e,f)===false){f.global&&B.active--;return }if(e.aborted){return }var S=0;var X=0;var R=V.clk;if(R){var W=R.name;if(W&&!R.disabled){O.extraData=O.extraData||{};O.extraData[W]=R.value;if(R.type=="image"){O.extraData[name+".x"]=V.clk_x;O.extraData[name+".y"]=V.clk_y}}}setTimeout(function(){var i=P.attr("target"),g=P.attr("action");V.setAttribute("target",U);if(V.getAttribute("method")!="POST"){V.setAttribute("method","POST")}if(V.getAttribute("action")!=T.url){V.setAttribute("action",T.url)}if(!O.skipEncodingOverride){P.attr({encoding:"multipart/form-data",enctype:"multipart/form-data"})}if(T.timeout){setTimeout(function(){X=true;Y()},T.timeout)}var h=[];try{if(O.extraData){for(var j in O.extraData){h.push(B('<input type="hidden" name="'+j+'" value="'+O.extraData[j]+'" />').appendTo(V)[0])}}b.appendTo("body");d.attachEvent?d.attachEvent("onload",Y):d.addEventListener("load",Y,false);V.submit()}finally{V.setAttribute("action",g);i?V.setAttribute("target",i):P.removeAttr("target");B(h).remove()}},10);var Z=0;function Y(){if(S++){return }d.detachEvent?d.detachEvent("onload",Y):d.removeEventListener("load",Y,false);var h=true;try{if(X){throw"timeout"}var i,k;k=d.contentWindow?d.contentWindow.document:d.contentDocument?d.contentDocument:d.document;if((k.body==null||k.body.innerHTML=="")&&!Z){Z=1;S--;setTimeout(Y,100);return }e.responseText=k.body?k.body.innerHTML:null;e.responseXML=k.XMLDocument?k.XMLDocument:k;e.getResponseHeader=function(m){var l={"content-type":T.dataType};return l[m]};if(T.dataType=="json"||T.dataType=="script"){var g=k.getElementsByTagName("textarea")[0];e.responseText=g?g.value:e.responseText}else{if(T.dataType=="xml"&&!e.responseXML&&e.responseText!=null){e.responseXML=a(e.responseText)}}i=B.httpData(e,T.dataType)}catch(j){h=false;B.handleError(T,e,"error",j)}if(h){T.success(i,"success");if(c){B.event.trigger("ajaxSuccess",[e,T])}}if(c){B.event.trigger("ajaxComplete",[e,T])}if(c&&!--B.active){B.event.trigger("ajaxStop")}if(T.complete){T.complete(e,h?"success":"error")}setTimeout(function(){b.remove();e.responseXML=null},100)}function a(g,h){if(window.ActiveXObject){h=new ActiveXObject("Microsoft.XMLDOM");h.async="false";h.loadXML(g)}else{h=(new DOMParser()).parseFromString(g,"text/xml")}return(h&&h.documentElement&&h.documentElement.tagName!="parsererror")?h:null}}};B.fn.ajaxForm=function(C){return this.ajaxFormUnbind().bind("submit.form-plugin",function(){B(this).ajaxSubmit(C);return false}).each(function(){B(":submit,input:image",this).bind("click.form-plugin",function(E){var D=this.form;D.clk=this;if(this.type=="image"){if(E.offsetX!=undefined){D.clk_x=E.offsetX;D.clk_y=E.offsetY}else{if(typeof B.fn.offset=="function"){var F=B(this).offset();D.clk_x=E.pageX-F.left;D.clk_y=E.pageY-F.top}else{D.clk_x=E.pageX-this.offsetLeft;D.clk_y=E.pageY-this.offsetTop}}}setTimeout(function(){D.clk=D.clk_x=D.clk_y=null},10)})})};B.fn.ajaxFormUnbind=function(){this.unbind("submit.form-plugin");return this.each(function(){B(":submit,input:image",this).unbind("click.form-plugin")})};B.fn.formToArray=function(N){var M=[];if(this.length==0){return M}var D=this[0];var H=N?D.getElementsByTagName("*"):D.elements;if(!H){return M}for(var I=0,K=H.length;I<K;I++){var E=H[I];var F=E.name;if(!F){continue}if(N&&D.clk&&E.type=="image"){if(!E.disabled&&D.clk==E){M.push({name:F,value:B(E).val()});M.push({name:F+".x",value:D.clk_x},{name:F+".y",value:D.clk_y})}continue}var O=B.fieldValue(E,true);if(O&&O.constructor==Array){for(var G=0,C=O.length;G<C;G++){M.push({name:F,value:O[G]})}}else{if(O!==null&&typeof O!="undefined"){M.push({name:F,value:O})}}}if(!N&&D.clk){var J=B(D.clk),L=J[0],F=L.name;if(F&&!L.disabled&&L.type=="image"){M.push({name:F,value:J.val()});M.push({name:F+".x",value:D.clk_x},{name:F+".y",value:D.clk_y})}}return M};B.fn.formSerialize=function(C){return B.param(this.formToArray(C))};B.fn.fieldSerialize=function(D){var C=[];this.each(function(){var H=this.name;if(!H){return }var F=B.fieldValue(this,D);if(F&&F.constructor==Array){for(var G=0,E=F.length;G<E;G++){C.push({name:H,value:F[G]})}}else{if(F!==null&&typeof F!="undefined"){C.push({name:this.name,value:F})}}});return B.param(C)};B.fn.fieldValue=function(H){for(var G=[],E=0,C=this.length;E<C;E++){var F=this[E];var D=B.fieldValue(F,H);if(D===null||typeof D=="undefined"||(D.constructor==Array&&!D.length)){continue}D.constructor==Array?B.merge(G,D):G.push(D)}return G};B.fieldValue=function(C,I){var E=C.name,N=C.type,O=C.tagName.toLowerCase();if(typeof I=="undefined"){I=true}if(I&&(!E||C.disabled||N=="reset"||N=="button"||(N=="checkbox"||N=="radio")&&!C.checked||(N=="submit"||N=="image")&&C.form&&C.form.clk!=C||O=="select"&&C.selectedIndex==-1)){return null}if(O=="select"){var J=C.selectedIndex;if(J<0){return null}var L=[],D=C.options;var G=(N=="select-one");var K=(G?J+1:D.length);for(var F=(G?J:0);F<K;F++){var H=D[F];if(H.selected){var M=H.value;if(!M){M=(H.attributes&&H.attributes.value&&!(H.attributes.value.specified))?H.text:H.value}if(G){return M}L.push(M)}}return L}return C.value};B.fn.clearForm=function(){return this.each(function(){B("input,select,textarea",this).clearFields()})};B.fn.clearFields=B.fn.clearInputs=function(){return this.each(function(){var D=this.type,C=this.tagName.toLowerCase();if(D=="text"||D=="password"||C=="textarea"){this.value=""}else{if(D=="checkbox"||D=="radio"){this.checked=false}else{if(C=="select"){this.selectedIndex=-1}}}})};B.fn.resetForm=function(){return this.each(function(){if(typeof this.reset=="function"||(typeof this.reset=="object"&&!this.reset.nodeType)){this.reset()}})};B.fn.enable=function(C){if(C==undefined){C=true}return this.each(function(){this.disabled=!C})};B.fn.selected=function(C){if(C==undefined){C=true}return this.each(function(){var D=this.type;if(D=="checkbox"||D=="radio"){this.checked=C}else{if(this.tagName.toLowerCase()=="option"){var E=B(this).parent("select");if(C&&E[0]&&E[0].type=="select-one"){E.find("option").selected(false)}this.selected=C}}})};function A(){if(B.fn.ajaxSubmit.debug&&window.console&&window.console.log){window.console.log("[jquery.form] "+Array.prototype.join.call(arguments,""))}}})(jQuery);

/**
 * jQuery validation plug-in 1.5.5
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2008 JÃ¶rn Zaefferer
 *
 * $Id: jquery.validate.js 6403 2009-06-17 14:27:16Z joern.zaefferer $
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function(A){A.extend(A.fn,{validate:function(B){if(!this.length){B&&B.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing");return }var C=A.data(this[0],"validator");if(C){return C}C=new A.validator(B,this[0]);A.data(this[0],"validator",C);if(C.settings.onsubmit){this.find("input, button").filter(".cancel").click(function(){C.cancelSubmit=true});if(C.settings.submitHandler){this.find("input, button").filter(":submit").click(function(){C.submitButton=this})}this.submit(function(D){if(C.settings.debug){D.preventDefault()}function E(){if(C.settings.submitHandler){if(C.submitButton){var F=A("<input type='hidden'/>").attr("name",C.submitButton.name).val(C.submitButton.value).appendTo(C.currentForm)}C.settings.submitHandler.call(C,C.currentForm);if(C.submitButton){F.remove()}return false}return true}if(C.cancelSubmit){C.cancelSubmit=false;return E()}if(C.form()){if(C.pendingRequest){C.formSubmitted=true;return false}return E()}else{C.focusInvalid();return false}})}return C},valid:function(){if(A(this[0]).is("form")){return this.validate().form()}else{var C=true;var B=A(this[0].form).validate();this.each(function(){C&=B.element(this)});return C}},removeAttrs:function(D){var B={},C=this;A.each(D.split(/\s/),function(E,F){B[F]=C.attr(F);C.removeAttr(F)});return B},rules:function(E,B){var G=this[0];if(E){var D=A.data(G.form,"validator").settings;var I=D.rules;var J=A.validator.staticRules(G);switch(E){case"add":A.extend(J,A.validator.normalizeRule(B));I[G.name]=J;if(B.messages){D.messages[G.name]=A.extend(D.messages[G.name],B.messages)}break;case"remove":if(!B){delete I[G.name];return J}var H={};A.each(B.split(/\s/),function(K,L){H[L]=J[L];delete J[L]});return H}}var F=A.validator.normalizeRules(A.extend({},A.validator.metadataRules(G),A.validator.classRules(G),A.validator.attributeRules(G),A.validator.staticRules(G)),G);if(F.required){var C=F.required;delete F.required;F=A.extend({required:C},F)}return F}});A.extend(A.expr[":"],{blank:function(B){return !A.trim(B.value)},filled:function(B){return !!A.trim(B.value)},unchecked:function(B){return !B.checked}});A.validator=function(B,C){this.settings=A.extend({},A.validator.defaults,B);this.currentForm=C;this.init()};A.validator.format=function(B,C){if(arguments.length==1){return function(){var D=A.makeArray(arguments);D.unshift(B);return A.validator.format.apply(this,D)}}if(arguments.length>2&&C.constructor!=Array){C=A.makeArray(arguments).slice(1)}if(C.constructor!=Array){C=[C]}A.each(C,function(D,E){B=B.replace(new RegExp("\\{"+D+"\\}","g"),E)});return B};A.extend(A.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusInvalid:true,errorContainer:A([]),errorLabelContainer:A([]),onsubmit:true,ignore:[],ignoreTitle:false,onfocusin:function(B){this.lastActive=B;if(this.settings.focusCleanup&&!this.blockFocusCleanup){this.settings.unhighlight&&this.settings.unhighlight.call(this,B,this.settings.errorClass,this.settings.validClass);this.errorsFor(B).hide()}},onfocusout:function(B){if(!this.checkable(B)&&(B.name in this.submitted||!this.optional(B))){this.element(B)}},onkeyup:function(B){if(B.name in this.submitted||B==this.lastElement){this.element(B)}},onclick:function(B){if(B.name in this.submitted){this.element(B)}},highlight:function(D,B,C){A(D).addClass(B).removeClass(C)},unhighlight:function(D,B,C){A(D).removeClass(B).addClass(C)}},setDefaults:function(B){A.extend(A.validator.defaults,B)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",dateDE:"Bitte geben Sie ein gŸltiges Datum ein.",number:"Please enter a valid number.",numberDE:"Bitte geben Sie eine Nummer ein.",digits:"Please enter only digits",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",accept:"Please enter a value with a valid extension.",maxlength:A.validator.format("Please enter no more than {0} characters."),minlength:A.validator.format("Please enter at least {0} characters."),rangelength:A.validator.format("Please enter a value between {0} and {1} characters long."),range:A.validator.format("Please enter a value between {0} and {1}."),max:A.validator.format("Please enter a value less than or equal to {0}."),min:A.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:false,prototype:{init:function(){this.labelContainer=A(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||A(this.currentForm);this.containers=A(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var B=(this.groups={});A.each(this.settings.groups,function(E,F){A.each(F.split(/\s/),function(H,G){B[G]=E})});var D=this.settings.rules;A.each(D,function(E,F){D[E]=A.validator.normalizeRule(F)});function C(F){var E=A.data(this[0].form,"validator");E.settings["on"+F.type]&&E.settings["on"+F.type].call(E,this[0])}A(this.currentForm).delegate("focusin focusout keyup",":text, :password, :file, select, textarea",C).delegate("click",":radio, :checkbox",C);if(this.settings.invalidHandler){A(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler)}},form:function(){this.checkForm();A.extend(this.submitted,this.errorMap);this.invalid=A.extend({},this.errorMap);if(!this.valid()){A(this.currentForm).triggerHandler("invalid-form",[this])}this.showErrors();return this.valid()},checkForm:function(){this.prepareForm();for(var B=0,C=(this.currentElements=this.elements());C[B];B++){this.check(C[B])}return this.valid()},element:function(C){C=this.clean(C);this.lastElement=C;this.prepareElement(C);this.currentElements=A(C);var B=this.check(C);if(B){delete this.invalid[C.name]}else{this.invalid[C.name]=true}if(!this.numberOfInvalids()){this.toHide=this.toHide.add(this.containers)}this.showErrors();return B},showErrors:function(C){if(C){A.extend(this.errorMap,C);this.errorList=[];for(var B in C){this.errorList.push({message:C[B],element:this.findByName(B)[0]})}this.successList=A.grep(this.successList,function(D){return !(D.name in C)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){if(A.fn.resetForm){A(this.currentForm).resetForm()}this.submitted={};this.prepareForm();this.hideErrors();this.elements().removeClass(this.settings.errorClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(D){var C=0;for(var B in D){C++}return C},hideErrors:function(){this.addWrapper(this.toHide).hide()},valid:function(){return this.size()==0},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid){try{A(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus()}catch(B){}}},findLastActive:function(){var B=this.lastActive;return B&&A.grep(this.errorList,function(C){return C.element.name==B.name}).length==1&&B},elements:function(){var C=this,B={};return A([]).add(this.currentForm.elements).filter(":input").not(":submit, :reset, :image, [disabled], :hidden").not(this.settings.ignore).filter(function(){!this.name&&C.settings.debug&&window.console&&console.error("%o has no name assigned",this);if(this.name in B||!C.objectLength(A(this).rules())){return false}B[this.name]=true;return true})},clean:function(B){return A(B)[0]},errors:function(){return A(this.settings.errorElement+"."+this.settings.errorClass,this.errorContext)},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=A([]);this.toHide=A([]);this.formSubmitted=false;this.currentElements=A([])},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers)},prepareElement:function(B){this.reset();this.toHide=this.errorsFor(B)},check:function(C){C=this.clean(C);if(this.checkable(C)){C=this.findByName(C.name)[0]}var G=A(C).rules();var D=false;for(method in G){var F={method:method,parameters:G[method]};try{var B=A.validator.methods[method].call(this,C.value.replace(/\r/g,""),C,F.parameters);if(B=="dependency-mismatch"){D=true;continue}D=false;if(B=="pending"){this.toHide=this.toHide.not(this.errorsFor(C));return }if(!B){this.formatAndAdd(C,F);return false}}catch(E){this.settings.debug&&window.console&&console.log("exception occured when checking element "+C.id+", check the '"+F.method+"' method");throw E}}if(D){return }if(this.objectLength(G)){this.successList.push(C)}return true},customMetaMessage:function(B,D){if(!A.metadata){return }var C=this.settings.meta?A(B).metadata()[this.settings.meta]:A(B).metadata();return C&&C.messages&&C.messages[D]},customMessage:function(C,D){var B=this.settings.messages[C];return B&&(B.constructor==String?B:B[D])},findDefined:function(){for(var B=0;B<arguments.length;B++){if(arguments[B]!==undefined){return arguments[B]}}return undefined},defaultMessage:function(B,C){return this.findDefined(this.customMessage(B.name,C),this.customMetaMessage(B,C),!this.settings.ignoreTitle&&B.title||undefined,A.validator.messages[C],"<strong>Warning: No message defined for "+B.name+"</strong>")},formatAndAdd:function(B,D){var C=this.defaultMessage(B,D.method);if(typeof C=="function"){C=C.call(this,D.parameters,B)}this.errorList.push({message:C,element:B});this.errorMap[B.name]=C;this.submitted[B.name]=C},addWrapper:function(B){if(this.settings.wrapper){B=B.add(B.parent(this.settings.wrapper))}return B},defaultShowErrors:function(){for(var C=0;this.errorList[C];C++){var B=this.errorList[C];this.settings.highlight&&this.settings.highlight.call(this,B.element,this.settings.errorClass,this.settings.validClass);this.showLabel(B.element,B.message)}if(this.errorList.length){this.toShow=this.toShow.add(this.containers)}if(this.settings.success){for(var C=0;this.successList[C];C++){this.showLabel(this.successList[C])}}if(this.settings.unhighlight){for(var C=0,D=this.validElements();D[C];C++){this.settings.unhighlight.call(this,D[C],this.settings.errorClass,this.settings.validClass)}}this.toHide=this.toHide.not(this.toShow);this.hideErrors();this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return A(this.errorList).map(function(){return this.element})},showLabel:function(C,D){var B=this.errorsFor(C);if(B.length){B.removeClass().addClass(this.settings.errorClass);B.attr("generated")&&B.html(D)}else{B=A("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(C),generated:true}).addClass(this.settings.errorClass).html(D||"");if(this.settings.wrapper){B=B.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()}if(!this.labelContainer.append(B).length){this.settings.errorPlacement?this.settings.errorPlacement(B,A(C)):B.insertAfter(C)}}if(!D&&this.settings.success){B.text("");typeof this.settings.success=="string"?B.addClass(this.settings.success):this.settings.success(B)}this.toShow=this.toShow.add(B)},errorsFor:function(B){return this.errors().filter("[for='"+this.idOrName(B)+"']")},idOrName:function(B){return this.groups[B.name]||(this.checkable(B)?B.name:B.id||B.name)},checkable:function(B){return/radio|checkbox/i.test(B.type)},findByName:function(B){var C=this.currentForm;return A(document.getElementsByName(B)).map(function(D,E){return E.form==C&&E.name==B&&E||null})},getLength:function(C,B){switch(B.nodeName.toLowerCase()){case"select":return A("option:selected",B).length;case"input":if(this.checkable(B)){return this.findByName(B.name).filter(":checked").length}}return C.length},depend:function(C,B){return this.dependTypes[typeof C]?this.dependTypes[typeof C](C,B):true},dependTypes:{"boolean":function(C,B){return C},string:function(C,B){return !!A(C,B.form).length},"function":function(C,B){return C(B)}},optional:function(B){return !A.validator.methods.required.call(this,A.trim(B.value),B)&&"dependency-mismatch"},startRequest:function(B){if(!this.pending[B.name]){this.pendingRequest++;this.pending[B.name]=true}},stopRequest:function(B,C){this.pendingRequest--;if(this.pendingRequest<0){this.pendingRequest=0}delete this.pending[B.name];if(C&&this.pendingRequest==0&&this.formSubmitted&&this.form()){A(this.currentForm).submit()}else{if(!C&&this.pendingRequest==0&&this.formSubmitted){A(this.currentForm).triggerHandler("invalid-form",[this])}}},previousValue:function(B){return A.data(B,"previousValue")||A.data(B,"previousValue",previous={old:null,valid:true,message:this.defaultMessage(B,"remote")})}},classRuleSettings:{required:{required:true},email:{email:true},url:{url:true},date:{date:true},dateISO:{dateISO:true},dateDE:{dateDE:true},number:{number:true},numberDE:{numberDE:true},digits:{digits:true},creditcard:{creditcard:true}},addClassRules:function(B,C){B.constructor==String?this.classRuleSettings[B]=C:A.extend(this.classRuleSettings,B)},classRules:function(C){var D={};var B=A(C).attr("class");B&&A.each(B.split(" "),function(){if(this in A.validator.classRuleSettings){A.extend(D,A.validator.classRuleSettings[this])}});return D},attributeRules:function(C){var E={};var B=A(C);for(method in A.validator.methods){var D=B.attr(method);if(D){E[method]=D}}if(E.maxlength&&/-1|2147483647|524288/.test(E.maxlength)){delete E.maxlength}return E},metadataRules:function(B){if(!A.metadata){return{}}var C=A.data(B.form,"validator").settings.meta;return C?A(B).metadata()[C]:A(B).metadata()},staticRules:function(C){var D={};var B=A.data(C.form,"validator");if(B.settings.rules){D=A.validator.normalizeRule(B.settings.rules[C.name])||{}}return D},normalizeRules:function(C,B){A.each(C,function(F,E){if(E===false){delete C[F];return }if(E.param||E.depends){var D=true;switch(typeof E.depends){case"string":D=!!A(E.depends,B.form).length;break;case"function":D=E.depends.call(B,B);break}if(D){C[F]=E.param!==undefined?E.param:true}else{delete C[F]}}});A.each(C,function(D,E){C[D]=A.isFunction(E)?E(B):E});A.each(["minlength","maxlength","min","max"],function(){if(C[this]){C[this]=Number(C[this])}});A.each(["rangelength","range"],function(){if(C[this]){C[this]=[Number(C[this][0]),Number(C[this][1])]}});if(A.validator.autoCreateRanges){if(C.min&&C.max){C.range=[C.min,C.max];delete C.min;delete C.max}if(C.minlength&&C.maxlength){C.rangelength=[C.minlength,C.maxlength];delete C.minlength;delete C.maxlength}}if(C.messages){delete C.messages}return C},normalizeRule:function(C){if(typeof C=="string"){var B={};A.each(C.split(/\s/),function(){B[this]=true});C=B}return C},addMethod:function(B,D,C){A.validator.methods[B]=D;A.validator.messages[B]=C||A.validator.messages[B];if(D.length<3){A.validator.addClassRules(B,A.validator.normalizeRule(B))}},methods:{required:function(D,C,E){if(!this.depend(E,C)){return"dependency-mismatch"}switch(C.nodeName.toLowerCase()){case"select":var B=A("option:selected",C);return B.length>0&&(C.type=="select-multiple"||(A.browser.msie&&!(B[0].attributes.value.specified)?B[0].text:B[0].value).length>0);case"input":if(this.checkable(C)){return this.getLength(D,C)>0}default:return A.trim(D).length>0}},remote:function(F,C,G){if(this.optional(C)){return"dependency-mismatch"}var D=this.previousValue(C);if(!this.settings.messages[C.name]){this.settings.messages[C.name]={}}this.settings.messages[C.name].remote=typeof D.message=="function"?D.message(F):D.message;G=typeof G=="string"&&{url:G}||G;if(D.old!==F){D.old=F;var B=this;this.startRequest(C);var E={};E[C.name]=F;A.ajax(A.extend(true,{url:G,mode:"abort",port:"validate"+C.name,dataType:"json",data:E,success:function(I){var J=I===true;if(J){var H=B.formSubmitted;B.prepareElement(C);B.formSubmitted=H;B.successList.push(C);B.showErrors()}else{var K={};K[C.name]=D.message=I||B.defaultMessage(C,"remote");B.showErrors(K)}D.valid=J;B.stopRequest(C,J)}},G));return"pending"}else{if(this.pending[C.name]){return"pending"}}return D.valid},minlength:function(C,B,D){return this.optional(B)||this.getLength(A.trim(C),B)>=D},maxlength:function(C,B,D){return this.optional(B)||this.getLength(A.trim(C),B)<=D},rangelength:function(D,B,E){var C=this.getLength(A.trim(D),B);return this.optional(B)||(C>=E[0]&&C<=E[1])},min:function(C,B,D){return this.optional(B)||C>=D},max:function(C,B,D){return this.optional(B)||C<=D},range:function(C,B,D){return this.optional(B)||(C>=D[0]&&C<=D[1])},email:function(C,B){return this.optional(B)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(C)},url:function(C,B){return this.optional(B)||/^(https?|ftp):\/\/(((([a-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-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(C)},date:function(C,B){return this.optional(B)||!/Invalid|NaN/.test(new Date(C))},dateISO:function(C,B){return this.optional(B)||/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(C)},dateDE:function(C,B){return this.optional(B)||/^\d\d?\.\d\d?\.\d\d\d?\d?$/.test(C)},number:function(C,B){return this.optional(B)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(C)},numberDE:function(C,B){return this.optional(B)||/^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(C)},digits:function(C,B){return this.optional(B)||/^\d+$/.test(C)},creditcard:function(F,C){if(this.optional(C)){return"dependency-mismatch"}if(/[^0-9-]+/.test(F)){return false}var G=0,E=0,B=false;F=F.replace(/\D/g,"");for(n=F.length-1;n>=0;n--){var D=F.charAt(n);var E=parseInt(D,10);if(B){if((E*=2)>9){E-=9}}G+=E;B=!B}return(G%10)==0},accept:function(C,B,D){D=typeof D=="string"?D.replace(/,/g,"|"):"png|jpe?g|gif";return this.optional(B)||C.match(new RegExp(".("+D+")$","i"))},equalTo:function(C,B,D){return C==A(D).val()}}});A.format=A.validator.format})(jQuery);(function(C){var B=C.ajax;var A={};C.ajax=function(E){E=C.extend(E,C.extend({},C.ajaxSettings,E));var D=E.port;if(E.mode=="abort"){if(A[D]){A[D].abort()}return(A[D]=B.apply(this,arguments))}return B.apply(this,arguments)}})(jQuery);(function(A){A.each({focus:"focusin",blur:"focusout"},function(C,B){A.event.special[B]={setup:function(){if(A.browser.msie){return false}this.addEventListener(C,A.event.special[B].handler,true)},teardown:function(){if(A.browser.msie){return false}this.removeEventListener(C,A.event.special[B].handler,true)},handler:function(D){arguments[0]=A.event.fix(D);arguments[0].type=B;return A.event.handle.apply(this,arguments)}}});A.extend(A.fn,{delegate:function(D,C,B){return this.bind(D,function(E){var F=A(E.target);if(F.is(C)){return B.apply(F,arguments)}})},triggerEvent:function(B,C){return this.triggerHandler(B,[A.event.fix({type:B,target:C})])}})})(jQuery);

// Gilt Group Customization:
jQuery.validator.defaults.ignore = [":hidden"];

/**
 * Additional Validation Methods for jQuery Validation Plugin
 *
 */
jQuery.validator.addMethod("maxWords",function(b,a,c){return this.optional(a)||b.match(/\b\w+\b/g).length<c},jQuery.validator.format("Please enter {0} words or less."));jQuery.validator.addMethod("minWords",function(b,a,c){return this.optional(a)||b.match(/\b\w+\b/g).length>=c},jQuery.validator.format("Please enter at least {0} words."));jQuery.validator.addMethod("rangeWords",function(b,a,c){return this.optional(a)||b.match(/\b\w+\b/g).length>=c[0]&&b.match(/bw+b/g).length<c[1]},jQuery.validator.format("Please enter between {0} and {1} words."));jQuery.validator.addMethod("letterswithbasicpunc",function(b,a){return this.optional(a)||/^[a-z-.,()'\"\s]+$/i.test(b)},"Letters or punctuation only please");jQuery.validator.addMethod("alphanumeric",function(b,a){return this.optional(a)||/^\w+$/i.test(b)},"Letters, numbers, spaces or underscores only please");jQuery.validator.addMethod("lettersonly",function(b,a){return this.optional(a)||/^[a-z]+$/i.test(b)},"Letters only please");jQuery.validator.addMethod("nowhitespace",function(b,a){return this.optional(a)||/^\S+$/i.test(b)},"No white space please");jQuery.validator.addMethod("ziprange",function(b,a){return this.optional(a)||/^90[2-5]\d\{2}-\d{4}$/.test(b)},"Your ZIP-code must be in the range 902xx-xxxx to 905-xx-xxxx");jQuery.validator.addMethod("vinUS",function(o){if(o.length!=17){return false}var h,a,l,j,b,k;var c=["A","B","C","D","E","F","G","H","J","K","L","M","N","P","R","S","T","U","V","W","X","Y","Z"];var m=[1,2,3,4,5,6,7,8,1,2,3,4,5,7,9,2,3,4,5,6,7,8,9];var g=[8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2];var e=0;for(h=0;h<17;h++){j=g[h];l=o.slice(h,h+1);if(h==8){k=l}if(!isNaN(l)){l*=j}else{for(a=0;a<c.length;a++){if(l.toUpperCase()===c[a]){l=m[a];l*=j;if(isNaN(k)&&a==8){k=c[a]}break}}}e+=l}b=e%11;if(b==10){b="X"}if(b==k){return true}return false},"The specified vehicle identification number (VIN) is invalid.");jQuery.validator.addMethod("dateITA",function(e,c){var a=false;var g=/^\d{1,2}\/\d{1,2}\/\d{4}$/;if(g.test(e)){var i=e.split("/");var d=parseInt(i[0],10);var b=parseInt(i[1],10);var f=parseInt(i[2],10);var h=new Date(f,b-1,d);if((h.getFullYear()==f)&&(h.getMonth()==b-1)&&(h.getDate()==d)){a=true}else{a=false}}else{a=false}return this.optional(c)||a},"Please enter a correct date");jQuery.validator.addMethod("dateNL",function(b,a){return this.optional(a)||/^\d\d?[\.\/-]\d\d?[\.\/-]\d\d\d?\d?$/.test(b)},"Vul hier een geldige datum in.");jQuery.validator.addMethod("time",function(b,a){return this.optional(a)||/^([01][0-9])|(2[0123]):([0-5])([0-9])$/.test(b)},"Please enter a valid time, between 00:00 and 23:59");jQuery.validator.addMethod("phone",function(a,b){a=a.replace(/\s+/g,"");return this.optional(b)||a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)},"Please specify a valid phone number");jQuery.validator.addMethod("strippedminlength",function(b,a,c){return jQuery(b).text().length>=c},jQuery.validator.format("Please enter at least {0} characters"));jQuery.validator.addMethod("email2",function(b,a,c){return this.optional(a)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)*(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(b)},jQuery.validator.messages.email);jQuery.validator.addMethod("url2",function(b,a,c){return this.optional(a)||/^(https?|ftp):\/\/(((([a-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-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)*(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(b)},jQuery.validator.messages.url);jQuery.validator.addMethod("creditcardtypes",function(b,a,c){if(/[^0-9-]+/.test(b)){return false}b=b.replace(/\D/g,"");var d=0;if(c.mastercard){d|=1}if(c.visa){d|=2}if(c.amex){d|=4}if(c.dinersclub){d|=8}if(c.enroute){d|=16}if(c.discover){d|=32}if(c.jcb){d|=64}if(c.unknown){d|=128}if(c.all){d=1|2|4|8|16|32|64|128}if(d&1&&/^(51|52|53|54|55)/.test(b)){return b.length==16}if(d&2&&/^(4)/.test(b)){return b.length==16}if(d&4&&/^(34|37)/.test(b)){return b.length==15}if(d&8&&/^(300|301|302|303|304|305|36|38)/.test(b)){return b.length==14}if(d&16&&/^(2014|2149)/.test(b)){return b.length==15}if(d&32&&/^(6011)/.test(b)){return b.length==16}if(d&64&&/^(3)/.test(b)){return b.length==16}if(d&64&&/^(2131|1800)/.test(b)){return b.length==15}if(d&128){return true}return false},"Please enter a valid credit card number.");

/**
 * Gilt Groupe Custom Validators:
 */
jQuery.validator.addMethod("zipcode", function(value, element) {
    return this.optional(element) || /^\d{5}([\- ]?\d{4})?$/.test(value);
}, "Your ZIP-code is invalid");

jQuery.validator.addMethod("phone_number", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, "");
	return this.optional(element) || /^(1-?)?\s*(\([2-9]\d{2}\)|[2-9]\d{2})(-?|\s*)[2-9]\d{2}(-?|\s*)\d{4}(\s*x?\d+)?$/.test(phone_number);
}, "Please specify a valid phone number");

// same as email, but accepts a csv of emails
jQuery.validator.addMethod("multiemail", function(value, element) {
    return this.optional(element) || /^(((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?\s*[,;]?\s*)+$/i.test(value);
}, jQuery.validator.messages.email);

jQuery.validator.addMethod("currencyUS", function(value, element) {
    return this.optional(element) || /^\$?\d+(\.\d{2})?$/.test(value);
}, "Please enter a valid dollar amount");

jQuery.validator.addMethod("creditcard2", function(value, element) {
    if (this.optional(element)) {
        return "dependency-mismatch";
    }
    // accept only digits and dashes and spaces
    if (/[^0-9\-\s]+/.test(value)) {
        return false;
    }
    var nCheck = 0,
        bEven = false;

    value = value.replace(/\D/g, "");

    for (n = value.length - 1; n >= 0; n--) {
        var cDigit = value.charAt(n);
        var nDigit = parseInt(cDigit, 10);
        if (bEven) {
            if ((nDigit *= 2) > 9)
                nDigit -= 9;
        }
        nCheck += nDigit;
        bEven = !bEven;
    }

    return (nCheck % 10) == 0;
}, jQuery.validator.messages.creditcard);

// Combines Luhn+5 & Prefix validation
jQuery.validator.addMethod("creditcard3", function(value, element, param) {
    if (this.optional(element)) {
        return "dependency-mismatch";
    }
    // accept only digits and dashes and spaces
	if (/[^0-9\-\s]+/.test(value)) {
        return false;
    }

	value = value.replace(/\D/g, "");

  if ("4222222222222" == value) { // Authorize.net force error code credit card number
    $(element).data("creditcardtype", "errorcode");
    return true;
  }

  var nCheck = 0,
      bEven = false;
  for (n = value.length - 1; n >= 0; n--) {
      var cDigit = value.charAt(n);
      var nDigit = parseInt(cDigit, 10);
      if (bEven) {
          if ((nDigit *= 2) > 9)
              nDigit -= 9;
      }
      nCheck += nDigit;
      bEven = !bEven;
  }

  if (nCheck % 10 != 0 && nCheck % 10 != 5) {
      $(element).data("creditcardtype", "checksum");
      return false;
  }

  param = jQuery.extend({}, jQuery.validator.methods.creditcard3.types, param);

	var validTypes = 0x0000;

    if (param.mastercard)
        validTypes |= 0x0001;
    if (param.visa)
        validTypes |= 0x0002;
    if (param["american express"])
        validTypes |= 0x0004;
    if (param.dinersclub)
        validTypes |= 0x0008;
    if (param.enroute)
        validTypes |= 0x0010;
    if (param.discover)
        validTypes |= 0x0020;
    if (param.jcb)
        validTypes |= 0x0040;
    if (param.unknown)
        validTypes |= 0x0080;
    if (param.all)
        validTypes = 0x0001 | 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020 | 0x0040 | 0x0080;

	if (validTypes & 0x0001 && /^(51|52|53|54|55)/.test(value)) { //mastercard
        $(element).data("creditcardtype", "mastercard");
		return value.length == 16;
	}
	if (validTypes & 0x0002 && /^(4)/.test(value)) { //visa
        $(element).data("creditcardtype", "visa");
		return value.length == 16;
	}
	if (validTypes & 0x0004 && /^(34|37)/.test(value)) { //amex
        $(element).data("creditcardtype", "american express");
		return value.length == 15;
	}
	if (validTypes & 0x0008 && /^(300|301|302|303|304|305|36|38)/.test(value)) { //dinersclub
        $(element).data("creditcardtype", "dinersclub");
		return value.length == 14;
	}
	if (validTypes & 0x0010 && /^(2014|2149)/.test(value)) { //enroute
        $(element).data("creditcardtype", "enroute");
		return value.length == 15;
	}
	if (validTypes & 0x0020 && /^(6011)/.test(value)) { //discover
        $(element).data("creditcardtype", "discover");
		return value.length == 16;
	}
	if (validTypes & 0x0040 && /^(3)/.test(value)) { //jcb
        $(element).data("creditcardtype", "jcb");
		return value.length == 16;
	}
	if (validTypes & 0x0040 && /^(2131|1800)/.test(value)) { //jcb
        $(element).data("creditcardtype", "jcb");
		return value.length == 15;
	}
    $(element).data("creditcardtype", "unknown");
	return (validTypes & 0x0080); //unknown
}, function(params, el) {
    return jQuery.validator.methods.creditcard3.messages[$(el).data("creditcardtype")];
});
jQuery.validator.methods.creditcard3.messages = {
    checksum: "Please enter a valid credit card number.",
    mastercard: "The credit card number you entered is not a valid Mastercard",
    visa: "The credit card number you entered is not a valid Visa card",
    "american express": "The credit card number you entered is not a valid American Express card",
    dinersclub: "The credit card number you entered is not a valid Diners Club card",
    enroute: "The credit card number you entered is not a valid Enroute card",
    discover: "The credit card number you entered is not a valid Discover card",
    jcb: "The credit card number you entered is not a valid JCB card",
    unknown: "The credit card number you entered is not recognized as a valid credit card."
};
jQuery.validator.methods.creditcard3.types = {
    mastercard: true,
    visa: true,
    "american express": true,
    dinersclub: false,
    enroute: false,
    discover: true,
    jcb: true,
    unknown: false
};

/**
 * jquery.Jcrop.js v0.9.8
 * jQuery Image Cropping Plugin
 * @author Kelly Hallman <khallman@gmail.com>
 * Copyright (c) 2008-2009 Kelly Hallman - released under MIT License
 */
(function(A){A.Jcrop=function(D,X){var D=D,X=X;if(typeof (D)!=="object"){D=A(D)[0]}if(typeof (X)!=="object"){X={}}if(!("trackDocument" in X)){X.trackDocument=A.browser.msie?false:true;if(A.browser.msie&&A.browser.version.split(".")[0]=="8"){X.trackDocument=true}}if(!("keySupport" in X)){X.keySupport=A.browser.msie?false:true}var t={trackDocument:false,baseClass:"jcrop",addClass:null,bgColor:"black",bgOpacity:0.6,borderOpacity:0.4,handleOpacity:0.5,handlePad:5,handleSize:9,handleOffset:5,edgeMargin:14,aspectRatio:0,keySupport:true,cornerHandles:true,sideHandles:true,drawBorders:true,dragEdges:true,boxWidth:0,boxHeight:0,boundary:8,animationDelay:20,swingSpeed:3,allowSelect:true,allowMove:true,allowResize:true,minSelect:[0,0],maxSize:[0,0],minSize:[0,0],onChange:function(){},onSelect:function(){}};var e=t;W(X);var v=A(D);var AL=v.clone().removeAttr("id").css({position:"absolute"});AL.width(v.width());AL.height(v.height());v.after(AL).hide();s(AL,e.boxWidth,e.boxHeight);var p=AL.width(),n=AL.height(),z=A("<div />").width(p).height(n).addClass(Z("holder")).css({position:"relative",backgroundColor:e.bgColor}).insertAfter(v).append(AL);if(e.addClass){z.addClass(e.addClass)}var f=A("<img />").attr("src",AL.attr("src")).css("position","absolute").width(p).height(n);var I=A("<div />").width(j(100)).height(j(100)).css({zIndex:310,position:"absolute",overflow:"hidden"}).append(f);var k=A("<div />").width(j(100)).height(j(100)).css("zIndex",320);var V=A("<div />").css({position:"absolute",zIndex:300}).insertBefore(AL).append(I,k);var R=e.boundary;var B=AE().width(p+(R*2)).height(n+(R*2)).css({position:"absolute",top:J(-R),left:J(-R),zIndex:290}).mousedown(AC);var U,AH,N,r;var l,E,L=true;var AD=a(AL),P,AN,AM,Y,AB;var AA=function(){var AQ=0,Ab=0,AP=0,Aa=0,AT,AR;function AV(Ae){var Ae=AS(Ae);AP=AQ=Ae[0];Aa=Ab=Ae[1]}function AU(Ae){var Ae=AS(Ae);AT=Ae[0]-AP;AR=Ae[1]-Aa;AP=Ae[0];Aa=Ae[1]}function Ad(){return[AT,AR]}function AO(Ag){var Af=Ag[0],Ae=Ag[1];if(0>AQ+Af){Af-=Af+AQ}if(0>Ab+Ae){Ae-=Ae+Ab}if(n<Aa+Ae){Ae+=n-(Aa+Ae)}if(p<AP+Af){Af+=p-(AP+Af)}AQ+=Af;AP+=Af;Ab+=Ae;Aa+=Ae}function AW(Ae){var Af=Ac();switch(Ae){case"ne":return[Af.x2,Af.y];case"nw":return[Af.x,Af.y];case"se":return[Af.x2,Af.y2];case"sw":return[Af.x,Af.y2]}}function Ac(){if(!e.aspectRatio){return AZ()}var Ag=e.aspectRatio,An=e.minSize[0]/l,Am=e.minSize[1]/E,Af=e.maxSize[0]/l,Ap=e.maxSize[1]/E,Ah=AP-AQ,Ao=Aa-Ab,Ai=Math.abs(Ah),Aj=Math.abs(Ao),Ak=Ai/Aj,Ae,Al;if(Af==0){Af=p*10}if(Ap==0){Ap=n*10}if(Ak<Ag){Al=Aa;w=Aj*Ag;Ae=Ah<0?AQ-w:w+AQ;if(Ae<0){Ae=0;h=Math.abs((Ae-AQ)/Ag);Al=Ao<0?Ab-h:h+Ab}else{if(Ae>p){Ae=p;h=Math.abs((Ae-AQ)/Ag);Al=Ao<0?Ab-h:h+Ab}}}else{Ae=AP;h=Ai/Ag;Al=Ao<0?Ab-h:Ab+h;if(Al<0){Al=0;w=Math.abs((Al-Ab)*Ag);Ae=Ah<0?AQ-w:w+AQ}else{if(Al>n){Al=n;w=Math.abs(Al-Ab)*Ag;Ae=Ah<0?AQ-w:w+AQ}}}if(Ae>AQ){if(Ae-AQ<An){Ae=AQ+An}else{if(Ae-AQ>Af){Ae=AQ+Af}}if(Al>Ab){Al=Ab+(Ae-AQ)/Ag}else{Al=Ab-(Ae-AQ)/Ag}}else{if(Ae<AQ){if(AQ-Ae<An){Ae=AQ-An}else{if(AQ-Ae>Af){Ae=AQ-Af}}if(Al>Ab){Al=Ab+(AQ-Ae)/Ag}else{Al=Ab-(AQ-Ae)/Ag}}}if(Ae<0){AQ-=Ae;Ae=0}else{if(Ae>p){AQ-=Ae-p;Ae=p}}if(Al<0){Ab-=Al;Al=0}else{if(Al>n){Ab-=Al-n;Al=n}}return last=AY(AX(AQ,Ab,Ae,Al))}function AS(Ae){if(Ae[0]<0){Ae[0]=0}if(Ae[1]<0){Ae[1]=0}if(Ae[0]>p){Ae[0]=p}if(Ae[1]>n){Ae[1]=n}return[Ae[0],Ae[1]]}function AX(Ah,Aj,Ag,Ai){var Al=Ah,Ak=Ag,Af=Aj,Ae=Ai;if(Ag<Ah){Al=Ag;Ak=Ah}if(Ai<Aj){Af=Ai;Ae=Aj}return[Math.round(Al),Math.round(Af),Math.round(Ak),Math.round(Ae)]}function AZ(){var Af=AP-AQ;var Ae=Aa-Ab;if(U&&(Math.abs(Af)>U)){AP=(Af>0)?(AQ+U):(AQ-U)}if(AH&&(Math.abs(Ae)>AH)){Aa=(Ae>0)?(Ab+AH):(Ab-AH)}if(r&&(Math.abs(Ae)<r)){Aa=(Ae>0)?(Ab+r):(Ab-r)}if(N&&(Math.abs(Af)<N)){AP=(Af>0)?(AQ+N):(AQ-N)}if(AQ<0){AP-=AQ;AQ-=AQ}if(Ab<0){Aa-=Ab;Ab-=Ab}if(AP<0){AQ-=AP;AP-=AP}if(Aa<0){Ab-=Aa;Aa-=Aa}if(AP>p){var Ag=AP-p;AQ-=Ag;AP-=Ag}if(Aa>n){var Ag=Aa-n;Ab-=Ag;Aa-=Ag}if(AQ>p){var Ag=AQ-n;Aa-=Ag;Ab-=Ag}if(Ab>n){var Ag=Ab-n;Aa-=Ag;Ab-=Ag}return AY(AX(AQ,Ab,AP,Aa))}function AY(Ae){return{x:Ae[0],y:Ae[1],x2:Ae[2],y2:Ae[3],w:Ae[2]-Ae[0],h:Ae[3]-Ae[1]}}return{flipCoords:AX,setPressed:AV,setCurrent:AU,getOffset:Ad,moveOffset:AO,getCorner:AW,getFixed:Ac}}();var x=function(){var AV,AR,Ab,Aa,Aj=370;var AU={};var An={};var AQ=false;var AZ=e.handleOffset;if(e.drawBorders){AU={top:AW("hline").css("top",A.browser.msie?J(-1):J(0)),bottom:AW("hline"),left:AW("vline"),right:AW("vline")}}if(e.dragEdges){An.t=Ai("n");An.b=Ai("s");An.r=Ai("e");An.l=Ai("w")}e.sideHandles&&Ae(["n","s","e","w"]);e.cornerHandles&&Ae(["sw","nw","ne","se"]);function AW(Aq){var Ar=A("<div />").css({position:"absolute",opacity:e.borderOpacity}).addClass(Z(Aq));I.append(Ar);return Ar}function AP(Aq,Ar){var As=A("<div />").mousedown(C(Aq)).css({cursor:Aq+"-resize",position:"absolute",zIndex:Ar});k.append(As);return As}function Ac(Aq){return AP(Aq,Aj++).css({top:J(-AZ+1),left:J(-AZ+1),opacity:e.handleOpacity}).addClass(Z("handle"))}function Ai(As){var Av=e.handleSize,Aw=AZ,Au=Av,Ar=Av,At=Aw,Aq=Aw;switch(As){case"n":case"s":Ar=j(100);break;case"e":case"w":Au=j(100);break}return AP(As,Aj++).width(Ar).height(Au).css({top:J(-At+1),left:J(-Aq+1)})}function Ae(Aq){for(i in Aq){An[Aq[i]]=Ac(Aq[i])}}function Ag(Ax){var As=Math.round((Ax.h/2)-AZ),Ar=Math.round((Ax.w/2)-AZ),Av=west=-AZ+1,Au=Ax.w-AZ,At=Ax.h-AZ,Aq,Aw;"e" in An&&An.e.css({top:J(As),left:J(Au)})&&An.w.css({top:J(As)})&&An.s.css({top:J(At),left:J(Ar)})&&An.n.css({left:J(Ar)});"ne" in An&&An.ne.css({left:J(Au)})&&An.se.css({top:J(At),left:J(Au)})&&An.sw.css({top:J(At)});"b" in An&&An.b.css({top:J(At)})&&An.r.css({left:J(Au)})}function AY(Aq,Ar){f.css({top:J(-Ar),left:J(-Aq)});V.css({top:J(Ar),left:J(Aq)})}function Ap(Aq,Ar){V.width(Aq).height(Ar)}function AS(){var Aq=AA.getFixed();AA.setPressed([Aq.x,Aq.y]);AA.setCurrent([Aq.x2,Aq.y2]);Am()}function Am(){if(Aa){return AX()}}function AX(){var Aq=AA.getFixed();Ap(Aq.w,Aq.h);AY(Aq.x,Aq.y);e.drawBorders&&AU.right.css({left:J(Aq.w-1)})&&AU.bottom.css({top:J(Aq.h-1)});AQ&&Ag(Aq);Aa||Ao();e.onChange(y(Aq))}function Ao(){V.show();AL.css("opacity",e.bgOpacity);Aa=true}function Ak(){Al();V.hide();AL.css("opacity",1);Aa=false}function AO(){if(AQ){Ag(AA.getFixed());k.show()}}function Af(){AQ=true;if(e.allowResize){Ag(AA.getFixed());k.show();return true}}function Al(){AQ=false;k.hide()}function Ah(Aq){(Y=Aq)?Al():Af()}function Ad(){Ah(false);AS()}var AT=AE().mousedown(C("move")).css({cursor:"move",position:"absolute",zIndex:360});I.append(AT);Al();return{updateVisible:Am,update:AX,release:Ak,refresh:AS,setCursor:function(Aq){AT.css("cursor",Aq)},enableHandles:Af,enableOnly:function(){AQ=true},showHandles:AO,disableHandles:Al,animMode:Ah,done:Ad}}();var o=function(){var AP=function(){},AR=function(){},AQ=e.trackDocument;if(!AQ){B.mousemove(AO).mouseup(AS).mouseout(AS)}function AW(){B.css({zIndex:450});if(AQ){A(document).mousemove(AO).mouseup(AS)}}function AV(){B.css({zIndex:290});if(AQ){A(document).unbind("mousemove",AO).unbind("mouseup",AS)}}function AO(AX){AP(c(AX))}function AS(AX){AX.preventDefault();AX.stopPropagation();if(P){P=false;AR(c(AX));e.onSelect(y(AA.getFixed()));AV();AP=function(){};AR=function(){}}return false}function AT(AY,AX){P=true;AP=AY;AR=AX;AW();return false}function AU(AX){B.css("cursor",AX)}AL.before(B);return{activateHandlers:AT,setCursor:AU}}();var AK=function(){var AR=A('<input type="radio" />').css({position:"absolute",left:"-30px"}).keypress(AO).blur(AS),AT=A("<div />").css({position:"absolute",overflow:"hidden"}).append(AR);function AP(){if(e.keySupport){AR.show();AR.focus()}}function AS(AU){AR.hide()}function AQ(AV,AU,AW){if(e.allowMove){AA.moveOffset([AU,AW]);x.updateVisible()}AV.preventDefault();AV.stopPropagation()}function AO(AV){if(AV.ctrlKey){return true}AB=AV.shiftKey?true:false;var AU=AB?10:1;switch(AV.keyCode){case 37:AQ(AV,-AU,0);break;case 39:AQ(AV,AU,0);break;case 38:AQ(AV,0,-AU);break;case 40:AQ(AV,0,AU);break;case 27:x.release();break;case 9:return true}return nothing(AV)}if(e.keySupport){AT.insertBefore(AL)}return{watchKeys:AP}}();function J(AO){return""+parseInt(AO)+"px"}function j(AO){return""+parseInt(AO)+"%"}function Z(AO){return e.baseClass+"-"+AO}function a(AO){var AP=A(AO).offset();return[AP.left,AP.top]}function c(AO){return[(AO.pageX-AD[0]),(AO.pageY-AD[1])]}function b(AO){if(AO!=AN){o.setCursor(AO);AN=AO}}function F(AQ,AS){AD=a(AL);o.setCursor(AQ=="move"?AQ:AQ+"-resize");if(AQ=="move"){return o.activateHandlers(q(AS),M)}var AO=AA.getFixed();var AP=O(AQ);var AR=AA.getCorner(O(AP));AA.setPressed(AA.getCorner(AP));AA.setCurrent(AR);o.activateHandlers(d(AQ,AO),M)}function d(AP,AO){return function(AQ){if(!e.aspectRatio){switch(AP){case"e":AQ[1]=AO.y2;break;case"w":AQ[1]=AO.y2;break;case"n":AQ[0]=AO.x2;break;case"s":AQ[0]=AO.x2;break}}else{switch(AP){case"e":AQ[1]=AO.y+1;break;case"w":AQ[1]=AO.y+1;break;case"n":AQ[0]=AO.x+1;break;case"s":AQ[0]=AO.x+1;break}}AA.setCurrent(AQ);x.update()}}function q(AP){var AO=AP;AK.watchKeys();return function(AQ){AA.moveOffset([AQ[0]-AO[0],AQ[1]-AO[1]]);AO=AQ;x.update()}}function O(AO){switch(AO){case"n":return"sw";case"s":return"nw";case"e":return"nw";case"w":return"ne";case"ne":return"sw";case"nw":return"se";case"se":return"nw";case"sw":return"ne"}}function C(AO){return function(AP){if(e.disabled){return false}if((AO=="move")&&!e.allowMove){return false}P=true;F(AO,c(AP));AP.stopPropagation();AP.preventDefault();return false}}function s(AS,AP,AR){var AO=AS.width(),AQ=AS.height();if((AO>AP)&&AP>0){AO=AP;AQ=(AP/AS.width())*AS.height()}if((AQ>AR)&&AR>0){AQ=AR;AO=(AR/AS.height())*AS.width()}l=AS.width()/AO;E=AS.height()/AQ;AS.width(AO).height(AQ)}function y(AO){return{x:parseInt(AO.x*l),y:parseInt(AO.y*E),x2:parseInt(AO.x2*l),y2:parseInt(AO.y2*E),w:parseInt(AO.w*l),h:parseInt(AO.h*E)}}function M(AP){var AO=AA.getFixed();if(AO.w>e.minSelect[0]&&AO.h>e.minSelect[1]){x.enableHandles();x.done()}else{x.release()}o.setCursor(e.allowSelect?"crosshair":"default")}function AC(AO){if(e.disabled){return false}if(!e.allowSelect){return false}P=true;AD=a(AL);x.disableHandles();b("crosshair");var AP=c(AO);AA.setPressed(AP);o.activateHandlers(AJ,M);AK.watchKeys();x.update();AO.stopPropagation();AO.preventDefault();return false}function AJ(AO){AA.setCurrent(AO);x.update()}function AE(){var AO=A("<div></div>").addClass(Z("tracker"));A.browser.msie&&AO.css({opacity:0,backgroundColor:"white"});return AO}function Q(Af){var Aa=Af[0]/l,AP=Af[1]/E,AZ=Af[2]/l,AO=Af[3]/E;if(Y){return }var AY=AA.flipCoords(Aa,AP,AZ,AO);var Ad=AA.getFixed();var AR=initcr=[Ad.x,Ad.y,Ad.x2,Ad.y2];var AQ=e.animationDelay;var AW=AR[0];var AV=AR[1];var AZ=AR[2];var AO=AR[3];var Ac=AY[0]-initcr[0];var AT=AY[1]-initcr[1];var Ab=AY[2]-initcr[2];var AS=AY[3]-initcr[3];var AX=0;var AU=e.swingSpeed;x.animMode(true);var Ae=function(){return function(){AX+=(100-AX)/AU;AR[0]=AW+((AX/100)*Ac);AR[1]=AV+((AX/100)*AT);AR[2]=AZ+((AX/100)*Ab);AR[3]=AO+((AX/100)*AS);if(AX<100){Ag()}else{x.done()}if(AX>=99.8){AX=100}AI(AR)}}();function Ag(){window.setTimeout(Ae,AQ)}Ag()}function g(AO){AI([AO[0]/l,AO[1]/E,AO[2]/l,AO[3]/E])}function AI(AO){AA.setPressed([AO[0],AO[1]]);AA.setCurrent([AO[2],AO[3]]);x.update()}function W(AO){if(typeof (AO)!="object"){AO={}}e=A.extend(e,AO);if(typeof (e.onChange)!=="function"){e.onChange=function(){}}if(typeof (e.onSelect)!=="function"){e.onSelect=function(){}}}function H(){return y(AA.getFixed())}function AG(){return AA.getFixed()}function S(AO){W(AO);m()}function T(){e.disabled=true;x.disableHandles();x.setCursor("default");o.setCursor("default")}function u(){e.disabled=false;m()}function K(){x.done();o.activateHandlers(null,null)}function AF(){z.remove();v.show()}function m(AO){e.allowResize?AO?x.enableOnly():x.enableHandles():x.disableHandles();o.setCursor(e.allowSelect?"crosshair":"default");x.setCursor(e.allowMove?"move":"default");z.css("backgroundColor",e.bgColor);if("setSelect" in e){g(X.setSelect);x.done();delete (e.setSelect)}if("trueSize" in e){l=e.trueSize[0]/p;E=e.trueSize[1]/n}U=e.maxSize[0]||0;AH=e.maxSize[1]||0;N=e.minSize[0]||0;r=e.minSize[1]||0;if("outerImage" in e){AL.attr("src",e.outerImage);delete (e.outerImage)}x.refresh()}k.hide();m(true);var G={animateTo:Q,setSelect:g,setOptions:S,tellSelect:H,tellScaled:AG,disable:T,enable:u,cancel:K,focus:AK.watchKeys,getBounds:function(){return[p*l,n*E]},getWidgetSize:function(){return[p,n]},release:x.release,destroy:AF};v.data("Jcrop",G);return G};A.fn.Jcrop=function(C){function B(F){var E=C.useImg||F.src;var D=new Image();D.onload=function(){A.Jcrop(F,C)};D.src=E}if(typeof (C)!=="object"){C={}}this.each(function(){if(A(this).data("Jcrop")){if(C=="api"){return A(this).data("Jcrop")}else{A(this).data("Jcrop").setOptions(C)}}else{B(this)}});return this}})(jQuery);

/**
 * History - New Wave Browser History Management
 *
 * Copyright (c) 2008 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/History
 */
(function(a){a.ui=a.ui||{};a.ui.hmanager=new function(){var c={},e=function(){};var g=a(window),f=location.hash;function b(){return f.replace("#","")}var d;return{enable:function(){if(a.browser.msie&&parseInt(a.browser.version)<8){a(function(){d=a('<iframe id="ui-history-iframe" style="display: none;"></iframe>').prependTo(document.body)[0];d.contentWindow.document.open();d.contentWindow.document.close();if(b()){d.contentWindow.document.location.hash=b()}})}g.bind("hashchange",function(h){if(!d&&f==location.hash||d&&f==d.contentWindow.document.location.hash){return false}if(a.browser.msie&&parseInt(a.browser.version)<8){f=d.contentWindow.document.location.hash}else{f=location.hash}if(b()){c[b()]()}else{}});if(!(a.browser.msie&&parseInt(a.browser.version)>=8)){setInterval((a.browser.msie?function(){if(f!=d.contentWindow.document.location.hash){g.trigger("hashchange")}}:function(){if(f!=location.hash){g.trigger("hashchange")}else{}}),200)}},add:function(i,h){c[i]=h},go:function(h){if(h){if(a.browser.msie&&parseInt(a.browser.version)<8){d.contentWindow.document.open();d.contentWindow.document.close();d.contentWindow.document.location.hash=h}location.hash=h;g.trigger("hashchange")}else{console.log("TODO do default state")}}}};a.ui.history=function(){var b=Array.prototype.slice.call(arguments,1);a.ui.hmanager[arguments[0]].apply(a.ui.hmanager,b)}})(jQuery);

/**
 *  Ajax Autocomplete for jQuery, version 1.0.7
 *  (c) 2009 Tomas Kirda
 *
 *  Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.
 *  For details, see the web site: http://www.devbridge.com/projects/autocomplete/jquery/
 *
 *  Last Review: 07/27/2009
 */
(function($){$.fn.autocomplete=function(options){return this.each(function(){return new Autocomplete(this,options);});};var reEscape=new RegExp("(\\"+["/",".","*","+","?","|","(",")","[","]","{","}","\\"].join("|\\")+")","g");var fnFormatResult=function(value,data,currentValue){var pattern="("+currentValue.replace(reEscape,"\\$1")+")";return value.replace(new RegExp(pattern,"gi"),"<strong>$1</strong>");};var Autocomplete=function(el,options){this.el=$(el);this.el.attr("autocomplete","off");this.suggestions=[];this.data=[];this.badQueries=[];this.selectedIndex=-1;this.currentValue=this.el.val();this.intervalId=0;this.cachedResponse=[];this.onChangeInterval=null;this.ignoreValueChange=false;this.serviceUrl=options.serviceUrl;this.isLocal=false;this.options={autoSubmit:false,minChars:1,maxHeight:300,deferRequestBy:0,width:0,highlight:true,params:{},fnFormatResult:fnFormatResult,delimiter:null};if(options){$.extend(this.options,options);}if(this.options.lookup){this.isLocal=true;if($.isArray(this.options.lookup)){this.options.lookup={suggestions:this.options.lookup,data:[]};}}this.initialize();};Autocomplete.prototype={killerFn:null,initialize:function(){var me,zindex;me=this;zindex=Math.max.apply(null,$.map($("body > *"),function(e,n){var pos=$(e).css("position");if(pos==="absolute"||pos==="relative"){return parseInt($(e).css("z-index"),10)||1;}}));this.killerFn=function(e){if($(e.target).parents(".autocomplete").size()===0){me.killSuggestions();me.disableKillerFn();}};var uid=new Date().getTime();var autocompleteElId="Autocomplete_"+uid;if(!this.options.width){this.options.width=this.el.width();}this.mainContainerId="AutocompleteContainter_"+uid;$('<div id="'+this.mainContainerId+'" style="position:absolute;z-index:'+zindex+'"><div class="autocomplete-w1"><div class="autocomplete" id="'+autocompleteElId+'" style="display:none; width:'+this.options.width+'px;"></div></div></div>').appendTo("body");this.container=$("#"+autocompleteElId);this.fixPosition();if(window.opera){this.el.keypress(function(e){me.onKeyPress(e);});}else{this.el.keydown(function(e){me.onKeyPress(e);});}this.el.keyup(function(e){me.onKeyUp(e);});this.el.blur(function(){me.enableKillerFn();});this.el.focus(function(){me.fixPosition();});this.container.css({maxHeight:this.options.maxHeight+"px"});},fixPosition:function(){var offset=this.el.offset();$("#"+this.mainContainerId).css({top:(offset.top+this.el.innerHeight())+"px",left:offset.left+"px"});},enableKillerFn:function(){var me=this;$(document).bind("click",me.killerFn);},disableKillerFn:function(){var me=this;$(document).unbind("click",me.killerFn);},killSuggestions:function(){var me=this;this.stopKillSuggestions();this.intervalId=window.setInterval(function(){me.hide();me.stopKillSuggestions();},300);},stopKillSuggestions:function(){window.clearInterval(this.intervalId);},onKeyPress:function(e){if(!this.enabled){return;}switch(e.keyCode){case 27:this.el.val(this.currentValue);this.hide();break;case 9:case 13:if(this.selectedIndex===-1){this.hide();return;}this.select(this.selectedIndex);if(e.keyCode===9){return;}break;case 38:this.moveUp();break;case 40:this.moveDown();break;default:return;}e.stopImmediatePropagation();e.preventDefault();},onKeyUp:function(e){switch(e.keyCode){case 38:case 40:return;}clearInterval(this.onChangeInterval);if(this.currentValue!==this.el.val()){if(this.options.deferRequestBy>0){var me=this;this.onChangeInterval=setInterval(function(){me.onValueChange();},this.options.deferRequestBy);}else{this.onValueChange();}}},onValueChange:function(){clearInterval(this.onChangeInterval);this.currentValue=this.el.val();var q=this.getQuery(this.currentValue);this.selectedIndex=-1;if(this.ignoreValueChange){this.ignoreValueChange=false;return;}if(q===""||q.length<this.options.minChars){this.hide();}else{this.getSuggestions(q);}},getQuery:function(val){var d,arr;d=this.options.delimiter;if(!d){return $.trim(val);}arr=val.split(d);return $.trim(arr[arr.length-1]);},getSuggestionsLocal:function(q){var ret,arr,len,val;arr=this.options.lookup;len=arr.suggestions.length;ret={suggestions:[],data:[]};for(var i=0;i<len;i++){val=arr.suggestions[i];if(val.toLowerCase().indexOf(q.toLowerCase())===0){ret.suggestions.push(val);ret.data.push(arr.data[i]);}}return ret;},getSuggestions:function(q){var cr,me,ls;cr=this.isLocal?this.getSuggestionsLocal(q):this.cachedResponse[q];if(cr&&$.isArray(cr.suggestions)){this.suggestions=cr.suggestions;this.data=cr.data;this.suggest();}else{if(!this.isBadQuery(q)){me=this;me.options.params.query=q;$.get(this.serviceUrl,me.options.params,function(txt){me.processResponse(txt);},"text");}}},isBadQuery:function(q){var i=this.badQueries.length;while(i--){if(q.indexOf(this.badQueries[i])===0){return true;}}return false;},hide:function(){this.enabled=false;this.selectedIndex=-1;this.container.hide();},suggest:function(){if(this.suggestions.length===0){this.hide();return;}var me,len,div,f;me=this;len=this.suggestions.length;f=this.options.fnFormatResult;v=this.getQuery(this.currentValue);this.container.hide().empty();for(var i=0;i<len;i++){div=$((me.selectedIndex===i?'<div class="selected"':"<div")+' title="'+this.suggestions[i]+'">'+f(this.suggestions[i],this.data[i],v)+"</div>");div.mouseover((function(xi){return function(){me.activate(xi);};})(i));div.click((function(xi){return function(){me.select(xi);};})(i));this.container.append(div);}this.enabled=true;this.container.show();},processResponse:function(text){var response;try{response=eval("("+text+")");}catch(err){return;}if(!$.isArray(response.data)){response.data=[];}this.cachedResponse[response.query]=response;if(response.suggestions.length===0){this.badQueries.push(response.query);}if(response.query===this.getQuery(this.currentValue)){this.suggestions=response.suggestions;this.data=response.data;this.suggest();}},activate:function(index){var divs=this.container.children();var activeItem;if(this.selectedIndex!==-1&&divs.length>this.selectedIndex){$(divs.get(this.selectedIndex)).attr("class","");}this.selectedIndex=index;if(this.selectedIndex!==-1&&divs.length>this.selectedIndex){activeItem=divs.get(this.selectedIndex);$(activeItem).attr("class","selected");}return activeItem;},deactivate:function(div,index){div.className="";if(this.selectedIndex===index){this.selectedIndex=-1;}},select:function(i){var selectedValue=this.suggestions[i];if(selectedValue){this.el.val(selectedValue);if(this.options.autoSubmit){var f=this.el.parents("form");if(f.length>0){f.get(0).submit();}}this.ignoreValueChange=true;this.hide();this.onSelect(i);}},moveUp:function(){if(this.selectedIndex===-1){return;}if(this.selectedIndex===0){this.container.children().get(0).className="";this.selectedIndex=-1;this.el.val(this.currentValue);return;}this.adjustScroll(this.selectedIndex-1);},moveDown:function(){if(this.selectedIndex===(this.suggestions.length-1)){return;}this.adjustScroll(this.selectedIndex+1);},adjustScroll:function(i){var activeItem,offsetTop,upperBound,lowerBound;activeItem=this.activate(i);offsetTop=activeItem.offsetTop;upperBound=this.container.scrollTop();lowerBound=upperBound+this.options.maxHeight-25;if(offsetTop<upperBound){this.container.scrollTop(offsetTop);}else{if(offsetTop>lowerBound){this.container.scrollTop(offsetTop-this.options.maxHeight+25);}}},onSelect:function(i){var me,onSelect,getValue,s,d;me=this;onSelect=me.options.onSelect;getValue=function(value){var del,currVal;del=me.options.delimiter;currVal=me.currentValue;if(!del){return value;}var arr=currVal.split(del);if(arr.length===1){return value;}return currVal.substr(0,currVal.length-arr[arr.length-1].length)+value;};s=me.suggestions[i];d=me.data[i];me.el.val(getValue(s));if($.isFunction(onSelect)){onSelect(s,d);}}};})(jQuery);

/**
 * Zoom plugin
 *
 * @version 0.9
 * @requires jQuery v1.3
 * @author Kevan Davis
 * @copyright Copyright (c) 2009, Gilt Groupe
 *
 * Distributed under the terms of the GNU General Public License
 * http://www.gnu.org/licenses/gpl-3.0.html
 *
 * Usage:
 *   $(".thumbnails").zoom({ container: $("#fullsizeimage") })
 *   With 1 or more thumbnail images selected, zoom will make it so when you are mousing over them, a fullsize version
 *   will pan around in a medium sized container.  Examples can be found on any product page at www.gilt.com
 *
 * Required parameters:
 *   container:  a jquery object for the full size image parent
 *
 * Optional parameters:
 *   triggerEvent:  the event that triggers the zoom effect, by default it's mouseover, but if you want, you can attach it to something else,
 *   easing:        easing function for the panning effect, default is "swing", "easeOutElastic" looks cool too
 *   panSpeed:      speed at which to pan around, default is "normal",
 *   zoomInSpeed:   speed at which to zoom in, default is "slow",
 *   zoomOutSpeed:  speed at which to zoom out, default is "fast",
 *   useZoomInEffect: whether or not to use the zoom in effect, default is true,
 *   useZoomOutEffect: whether or not to use the zoom out effect, default is true
 *
 * TODO: remaining bug:  if you zoomout from the bottom, it visibly moves from the left
 */
(function($) {
	$.fn.zoom = function(options) {
		var opts = $.extend({}, $.fn.zoom.defaults, options);
        var elements = $(this);
        var el;
        var data;
        var offset;

        // Preload the full size images, and get their dimensions
        elements.each(function(_, el) {
            var full = $("<img/>").attr("src", $(el).attr("fullsrc")).hide();
            full.load(function() {
                $(el).data("zoomed", { src: $(el).attr("fullsrc"), height: full.height(), width: full.width() });
            }).appendTo("body");
        });

        // Normalize zoom and pan speeds.  Need these in numeric form for some calculations
        if (opts.useZoomInEffect) {
            opts.zoomInSpeed = $.speed(opts.zoomInSpeed).duration;
            opts.panSpeed = $.speed(opts.panSpeed).duration;
        }

        if (!opts.container || opts.container.data("iszoomconfigured")) {
            return elements;
        }

        var img = opts.container.find("img");
        if (!img.length) {
            img = $("<img/>");
        }

        opts.container
            .data("iszoomconfigured",true)
            .empty()
            .css({ position: 'relative' })
            .append("<div/>")
            .children("div")
                .css({ overflow: 'hidden', position: 'relative', height: '100%', width: '100%' })
                .append(img)
                .children("img")
                    .css({ position: 'absolute', top: 0, left: 0 });

        var hide = (opts.container.filter(":hidden").length > 0);
        var zoomLastTS;
        var zoomElapsed;
        var started;
        var f = function(event) {
            if (!event.pageX && !event.pageY) {
                return;
            }

            var x = event.pageX;//||(el.width()/2 + offset.left);
            var y = event.pageY;//||(el.height()/2 + offset.top);

            var new_offset = {
                top:  ((y - offset.top) / el.height()) * 100.0,
                left: ((x - offset.left) / el.width()) * 100.0
            };
            var zoom = {
                top:  (data.height * new_offset.top / 100) - opts.container.height() / 2,
                left: (data.width * new_offset.left / 100) - opts.container.width() / 2

            };
            if (data.width - opts.container.width() < zoom.left) {
                zoom.left = data.width - opts.container.width();
            } else if (0 > zoom.left) {
                zoom.left = 0;
            }
            if (data.height - opts.container.height() < zoom.top) {
                zoom.top = data.height - opts.container.height();
            } else if (0 > zoom.top) {
                zoom.top = 0;
            }
            var css1;
            var css2 = {
                marginTop: -zoom.top,
                marginRight: data.width - zoom.left,
                marginBottom: data.height - zoom.top,
                marginLeft: -zoom.left
            };
            if (!started) {
                started = true;
                if (opts.useZoomInEffect) {
                    img.css({
                        marginTop: 0,
                        marginRight: 0,
                        marginBottom: 0,
                        marginLeft: 0
                    });
                } else {
                    img.stop(true,false).css(css2);
                    return;
                }
            }
            if (opts.useZoomInEffect) {
                var newTS = (new Date()).getTime();
                zoomElapsed += newTS - zoomLastTS;
                zoomLastTS = newTS;
                if (img.height() != data.height || img.width() != data.width) {
                    var ratio;
                    if (zoomElapsed < opts.zoomInSpeed) {
                        ratio = opts.panSpeed / (opts.zoomInSpeed - zoomElapsed);
                        if (1 < ratio) {
                            ratio = 1;
                        }
                        css1 = $.extend({}, css2, { height: data.height, width: data.width });
                    }
                }
            }
            img.stop(true, false);
            if (css1) {
                img.animate(css1, { duration: opts.zoomInSpeed - zoomElapsed, easing: "linear" });
            }
            img.animate(css2, { duration: opts.panSpeed, easing: opts.easing });
        };
        elements.bind(opts.triggerEvent,
            function() {
                el = $(this);
                offset = el.offset();
                data = el.data("zoomed");
                if (!data) {
                    return;
                }
                var newData = img.data("unzoomed");
                if (newData){
                    $.extend(newData, { src: img.attr("src") });
                } else {
                    newData = {
                        src: img.attr("src"),
                        height: img.height(),
                        width: img.width()
                    };
                }
                img.data("unzoomed", newData);
                img.attr("src", data.src)
                    .stop(true, true);
                if (!opts.useZoomInEffect) {
                    img.height(data.height)
                        .width(data.width);
                }
                if (hide) {
                    opts.container.show();
                }
                zoomLastTS = (new Date()).getTime();
                zoomElapsed = 0;
                started = false;
                $().mousemove(f).mousemove();
            }
        );
        return elements.mouseout(
            function() {
                $().unbind("mousemove", f);
                if (hide) {
                    opts.container.hide();
                }
                el = null;
                offset = null;
                data = img.data("unzoomed");
                if (!data) {
                    return;
                }
                img.attr("src", data.src)
                    .stop(true, false);
                if (opts.useZoomOutEffect) { // TODO: this part needs some work
                    img.animate({
                        margin: 0,
                        height: data.height,
                        width: data.width
                    }, { duration: opts.zoomOutSpeed });
                } else {
                    img.css({
                        margin: 0,
                        height: data.height,
                        width: data.width
                    });
                }
                data = null;
            }
        );
	};

	$.fn.zoom.defaults = {
        triggerEvent: "mouseover",
        easing: "swing",
        panSpeed: "normal",
        zoomInSpeed: "slow",
        zoomOutSpeed: "fast",
        useZoomInEffect: true,
        useZoomOutEffect: true
    };
})(jQuery);

/**
 * Rollover plugin
 *
 * @version 1.0
 * @requires jQuery v1.3
 * @author Kevan Davis
 * @copyright Copyright (c) 2009, Gilt Groupe
 *
 * Distributed under the terms of the GNU General Public License
 * http://www.gnu.org/licenses/gpl-3.0.html
 *
 */
(function($) {
	$.fn.rollover = function(options) {
		var opts = $.extend({}, $.fn.rollover.defaults, options);
        var elements = this;
        var i = elements.length;

        var fOver = function() {
            var j = opts.states.length;
            while (j--) {
                opts.states[j].element.attr("src", opts.states[j].rollover.attr("src"));
            }
        };
        var fOut = function() {
            var j = opts.states.length;
            while (j--) {
                opts.states[j].element.attr("src", opts.states[j].rollout);
            }
        };

        while (i--) {
            var el = $(elements[i]);
            if (el.attr(opts.rollover_source)) {
                var e = el.attr(opts.rollover_target);
                if (e) {
                    e = $(e);
                } else {
                    e = el;
                }
                opts.states.push({ rollover: $("<img/>").attr("src", el.attr(opts.rollover_source)), rollout: e.attr("src"), element: e });
            }
            if (el.attr(opts.otherrollover_sources) && el.attr(opts.otherrollover_targets)) {
                var srcs = el.attr(opts.otherrollover_sources).split(/[, ]/g);
                var targets = el.attr(opts.otherrollover_targets).split(/[, ]/g);
                var j = srcs.length;
                while (j--) {
                    var t = $(targets[j]);
                    if (!t.length) {
                        t = $("#" + targets[j]);
                    }
                    opts.states.push({ rollover: $("<img/>").attr("src", srcs[j]), rollout: t.attr("src"), element: t });
                }
            }
            el.hover(fOver, fOut);
        }

        return $(elements);
	};

	$.fn.rollover.defaults = {
        rollover_source: "rollSrc",
        rollover_target: "rollTarget",
        otherrollover_sources: "rolloverSources",
        otherrollover_targets: "rolloverTargets",
        states: []
	};
})(jQuery);

/**
 * @name Gilt Carousel Plugin
 */
(function($) {
  $.widget("ui.carousel", {
    _init: function() {
      var This = this;
      this.element
        .addClass(this.widgetBaseClass)
        .append(this.options.templates.leftArrow)
        .append(this.options.templates.rightArrow);
      if (this.options.showFooter) {
        var footer = $(this.options.templates.footer);
        footer
          .addClass(this.widgetBaseClass + "-footer")
          .find("span")
            .addClass(this.widgetBaseClass + "-footer-group")
            .append(this.options.templates.leftArrowSmall)
            .append(this.options.templates.rightArrowSmall)
          .end()
          .appendTo(this.element);
      }
      this.options.maxIndex = this.element.children("ul:first").children("li").length;
      for (var i = 0; i < this.element.children("ul").length; ++i) {
        if (!this.options.transitions[i]) {
          this.options.transitions[i] = $.extend({}, this.options.defaultTransition);
        } else if (!this.options.transitions[i].left) {
          var transition = this.options.transitions[i];
          this.options.transitions[i] = {
            left: transition,
            right: transition
          };
        }
      }
      for (i = 0; i < this.options.maxIndex; ++i) {
        this.element.children("ul").find("> li:eq(" + i + ")").addClass(this.widgetBaseClass + "-state-" + i);
        if (this.options.showFooter) {
          var numeral = $(this.options.templates.number);
          numeral
            .addClass("ui-icon-numeral-" + (i + 1) + (i == this.options.state ? " ui-state-active" : ""))
            .click((function(i) {
              return function() {
                This.frame(i);
                if (This.options.autoRotate) {
                  This.autorotate("stop");
                }
              };
            })(i))
            .html($.isFunction(this.options.customFooterTemplate) ? this.options.customFooterTemplate(i) : (i + 1))
            .insertBefore(footer.children("span").children(":last"));
        }
      }
      if (this.options.showFooter) {
        this.element.find("." + this.widgetBaseClass + "-footer-group").css({
          left: (this.element.find("." + this.widgetBaseClass + "-footer").width() - this.element.find("." + this.widgetBaseClass + "-footer-group").width()) / 2
        });
      }
      this.element
        .children("ul")
          .children("li")
            .hide()
            .filter("." + this.widgetBaseClass + "-state-" + this.options.state)
              .show()
            .end()
          .end()
        .end()
        .hover(
        function() {
          $(this).addClass("ui-state-hover");
          if (This.options.keyHandler) {
            $(document).bind("keydown", This, This._keyHandler);
          }
        },
        function() {
          $(this).removeClass("ui-state-hover");
          if (This.options.keyHandler) {
            $(document).unbind("keydown", This._keyHandler);
          }
        }
      ).find(".ui-icon").hover(
        function() {
          This.element.removeClass("ui-state-hover");
          $(this).addClass("ui-state-hover");
        },
        function() {
          This.element.addClass("ui-state-hover");
          $(this).removeClass("ui-state-hover");
        }
      ).filter(".ui-icon-arrow-1-w, .ui-icon-arrowthick-1-w")
         .click(function() {
           This.rotate("left");
           if (This.options.autoRotate) {
             This.autorotate("start", "left");
           }
         })
       .end()
       .filter(".ui-icon-arrow-1-e, .ui-icon-arrowthick-1-e")
         .click(function() {
           This.rotate("right");
           if (This.options.autoRotate) {
             This.autorotate("start", "right");
           }
         });
      if (this.options.autoRotate) {
        this.autorotate("start");
      }
    },
    frame: function(index, dir) {
      var old_index = this.options.state;
      if (index != old_index) {
        this.options.state = index;
        if (!dir) {
          dir = old_index - index;
          dir = dir / Math.abs(dir);
          dir = (1 == dir ? "left" : "right");
        }
        var dir2 = ("right" == dir ? "left" : "right");
        this.element.find(":animated").stop(true, true);
        var This = this;
        this.element.children("ul").each(function(i) {
          var transition = This.options.transitions[i];
          $.fn.show.apply($(this).children("li." + This.widgetBaseClass + "-state-" + index), transition[dir]);
          $.fn.hide.apply($(this).children("li." + This.widgetBaseClass + "-state-" + old_index), transition[dir2]);
        });
        this.element
          .find("." + this.widgetBaseClass + "-footer-group .ui-icon")
            .removeClass("ui-state-active")
            .filter(".ui-icon-numeral-" + (index + 1))
              .addClass("ui-state-active");
      }
      this._trigger("frame");
    },
    rotate: function(direction) {
      var new_index = this.options.state;
      if ("left" == direction) {
        new_index--;
        if (new_index < 0) {
          if (this.options.loop) {
            new_index = this.options.maxIndex - 1;
          } else {
            new_index = this.options.state;
          }
        }
      } else if ("right" == direction) {
        new_index++;
        if (new_index == this.options.maxIndex) {
          if (this.options.loop) {
            new_index = 0;
          } else {
            new_index = this.options.state;
          }
        }
      }
      this._trigger("rotate", null, { direction: direction });
      this.frame(new_index, direction);
    },
    autorotate: function(action, direction) {
      clearInterval(this.options.autoplayInterval);
      if ("start" == action) {
        if (this.options.autoRotateChangesDirection) {
          this.options.autoplayDirection = direction || this.options.autoRotateDefaultDirection;
        } else {
          this.options.autoplayDirection = this.options.autoRotateDefaultDirection;
        }
        var This = this;
        this.options.autoplayInterval = setInterval(function() {
          This.rotate(This.options.autoplayDirection);
        }, this.options.autoRotateInterval);
        this._trigger("autorotate-start");
      } else if ("stop" == action) {
        this._trigger("autorotate-stop");
      }
    },
    _keyHandler: function(ev) {
      var This = ev.data;
      if (37 == ev.keyCode) {
        This.rotate("left");
      } else if (39 == ev.keyCode) {
        This.rotate("right");
      } else if ((0 == ev.keyCode || (47 < ev.keyCode && 58 > ev.keyCode)) && 47 < ev.which && 58 > ev.which) {
        This.frame(ev.which - 49);
      } else if (13 == ev.keyCode || 32 == ev.keyCode || (0 == ev.keyCode && 32 == ev.which)) {
        document.location = This.element.find("li:visible a:first").attr("href");
      } else {
        return;
      }
      ev.preventDefault();
    }
  });
  $.ui.carousel.defaults = {
    autoRotate: true,
    autoRotateInterval: 10000,
    autoRotateDefaultDirection: "right",
    autoRotateChangesDirection: true,
    transitions: [],
    defaultTransition: {
      left: ["slide", { direction: "left", easing: "easeOutQuint" }],
      right: ["slide", { direction: "right", easing: "easeOutQuint" }]
    },
    loop: true,
    keyHandler: true,
    showFooter: true,
    state: 0,
    templates: {
      leftArrowSmall: "<span class='ui-icon ui-icon-arrow-1-w'>&lt;</span>",
      rightArrowSmall: "<span class='ui-icon ui-icon-arrow-1-e'>&gt;</span>",
      leftArrow: "<span class='ui-icon ui-icon-arrowthick-1-w'>&lt;</span>",
      rightArrow: "<span class='ui-icon ui-icon-arrowthick-1-e'>&gt;</span>",
      number: "<span class='ui-icon'></span>",
      footer: "<div><span></span></div>"
    }
  };
})(jQuery);

/** Gilt Groupe SizeChart Plugin
 *
 * @version 0.9
 * @requires jQuery v1.3, jQueryUI v1.7, Caret Plugin
 * @author Kevan Davis
 * @copyright Copyright (c) 2009, Gilt Groupe
 *
 * Distributed under the terms of the GNU General Public License
 * http://www.gnu.org/licenses/gpl-3.0.html
 *
 * @TODO: Compress it, once it's stable
 */
(function($) {
  $.widget("ui.sizechart", {
    _init: function() {
      if (!this.options.testElement) {
        this.options.testElement = this.element;
      }
      this.render();
      var sortStartIndex, sortStopIndex;
      var This = this;
      if (this.options.editable) {
        this.element.sortable({
          axis: 'y',
          containment: this.element,
          items: "tr",
          tolerance: 'pointer',
          start: function(ev, ui) {
            sortStartIndex = ui.item.prevAll().length;
            if (ui.item.parent("tbody").length) {
              sortStartIndex++;
            }
          },
          stop: function(ev, ui) {
            sortStopIndex = ui.item.prevAll().length;
            if (ui.item.parent("tbody").length && sortStartIndex) {
              sortStopIndex++;
            }
            var row = This.options.data.splice(sortStartIndex, 1)[0];
            This.options.data.splice(sortStopIndex, 0, row);
            if (ui.item.parent("thead").length) {
              This.element.find("tbody").prepend(This.element.find("thead tr:last"));
            } else if (!This.element.find("thead tr").length) {
              This.element.find("thead").prepend(This.element.find("tbody tr:first"));
            }
            This.render();
          }
        });
      }
    },
    _calcMinWidth: function(col) {
      var min = 0;
      var testTable = $(this.options.templates.table).appendTo(this.options.testElement);
      var testRow = $("<tr/>");
      testTable.append(testRow);
      for (var i = 0; i < this.options.data.length; ++i) {
        var test = $("<td>" + this.options.data[i].entries[col] + "</td>").appendTo(testRow);
        if (!this.options.padding) {
          this.options.padding = {
            l: parseInt(test.css("padding-left") || "0"),
            r: parseInt(test.css("padding-right") || "0"),
            t: parseInt(testTable.css("border-spacing") || "0")
          };
        }
        min = Math.max(min, test.width());
        test.remove();
      }
      testTable.remove();
      var changed = false;
      if (this.options.widths[col] != min) {
        changed = true;
      }
      this.options.widths[col] = min;
      return changed;
    },
    _calcColumnSets: function() {
      var sets = [];
      var colsRemaining = this.options.data[0].entries.length - this.options.repeatFirstNColumns;
      var sanity = 100;
      var nextCol = this.options.repeatFirstNColumns;
      var padding = this.options.padding;
      while (colsRemaining && sanity--) {
        var set = { snap: false, cols:[] };
        var curWidth = -padding.t;
        for (var i = 0; i < this.options.repeatFirstNColumns; ++i) {
          set.cols.push(i);
          curWidth += this.options.widths[i] + padding.l + padding.r + padding.t + this.options.fudgeFactor;
        }
        if (curWidth >= this.options.width) {
          throw "Min Width of Repeating Columns exceeds Max Width of the Table";
        }
        for (i = nextCol; i < this.options.data[0].entries.length; ++i) {
          if (curWidth + this.options.widths[i] + padding.l + padding.r + padding.t + this.options.fudgeFactor <= this.options.width) {
            set.cols.push(i);
            curWidth += this.options.widths[i] + padding.l + padding.r + padding.t + this.options.fudgeFactor;
            colsRemaining--;
            nextCol++;
          } else {
            break;
          }
        }
        set.width = curWidth;
        set.snap = (curWidth >= this.options.snapPoint);
        sets.push(set);
      }
      //console.debug(sets);
      return sets;
    },
    _clickCell: function() {
      var This = $(this).closest("table").parent().data("sizechart");
      if (!(This.options.sizeMode && this == This.element.find("td:first")[0])) {
        var wasrerendered = false;
        var t_row = $(this).closest('tr').prevAll().length;
        if ($(this).closest("tbody").length) {
          t_row++;
        }
        var t_col = $(this).closest("td").prevAll().length;
        $(this).closest("table").prevAll("table").each(function() {
          t_col += $(this).find("tr:first td").length - This.options.repeatFirstNColumns;
        });
        This.element.find("td input").each(function() {
          var row = $(this).closest('tr').prevAll().length;
          if ($(this).closest("tbody").length) {
            row++;
          }
          var col = $(this).closest("td").prevAll().length;
          if (col >= This.options.repeatFirstNColumns) {
            $(this).closest("table").prevAll("table").each(function() {
              col += $(this).find("tr:first td").length - This.options.repeatFirstNColumns;
            });
          }
          This.options.data[row].entries[col] = $(this).val();
          if (This._calcMinWidth(col)) {
            This.render();
            wasrerendered = true;
          }
          var p = $(this).parent();
          var extra = p.find("a");
          p.html($(this).val() || "&nbsp;").prepend(extra);
        });
        if (wasrerendered) {
          var t_check = 0;
          This.element.find("table").each(function() {
            t_check += $(this).find("tr:first td").length;
            if (t_check < t_col) {
              t_col += This.options.repeatFirstNColumns;
            } else {
              return false;
            }
          });
          This.element.find("table").find("tr:eq(" + t_row + ") td").eq(t_col).trigger("click");
          return;
        }
        var input = $("<input type='text'/>");
        var extra = $(this).find("a");
        $("body").append(extra);
        input.val($.trim($(this).text()));
        $(this).html("").append(input);
        input.before(extra);
        input.focus().blur(function() {
          $("body").append(extra);
          var p = input.parent();
          var row = p.parent().prevAll().length;
          if (p.closest("tbody").length) {
            row++;
          }
          var col = p.prevAll().length;
          if (col >= This.options.repeatFirstNColumns) {
            p.closest("table").prevAll("table").each(function() {
              col += $(this).find("tr:first td").length - This.options.repeatFirstNColumns;
            });
          }
          console.debug(col);
          This.options.data[row].entries[col] = input.val();
          if (This._calcMinWidth(col)) {
            This.render();
          }
          p.html(input.val() || "&nbsp;");
          p.prepend(extra);
        });
        if (This.options.editable) {
          input.keydown(function(ev) {
            switch (ev.which) {
              case 38: // up
                if (!ev.shiftKey && !input.caret()) {
                  ev.preventDefault();
                  if (input.closest("tr").prevAll("tr").length) {
                    target = input.closest("tr").prev("tr").find("td:eq(" + input.parent().prevAll("td").length + ")");
                    target.trigger("click");
                    input.blur();
                  } else if (input.closest("tbody").length) {
                    target = input.closest("table").find("thead td:eq(" + input.parent().prevAll("td").length + ")");
                    target.trigger("click");
                    input.blur();
                  }
                }
                break;
              case 40: // down
                if (!ev.shiftKey && input.caret() == input.val().length) {
                  ev.preventDefault();
                  if (ev.altKey && This.options.editable) {
                    var col = input.closest("td").prevAll().length;
                    This.addrow();
                    This.element.find("tr:eq(" + (This.element.find("tr").length - 2) + ") td:eq(" + col + ")").trigger("click");
                  }
                  if (input.closest("tr").nextAll("tr").length) {
                    target = input.closest("tr").next("tr").find("td:eq(" + input.parent().prevAll("td").length + ")");
                    target.trigger("click");
                    input.blur();
                  } else if (input.closest("thead").length) {
                    target = input.closest("table").find("tbody tr:first td:eq(" + input.parent().prevAll("td").length + ")");
                    target.trigger("click");
                    input.blur();
                  }
                }
                break;
              case 37: // left
                if (!ev.shiftKey && !input.caret()) {
                  ev.preventDefault();
                  if (input.parent().prevAll("td").length) {
                    var target = input.parent().prev("td");
                    target.trigger("click");
                    input.blur();
                  }
                }
                break;
              case 39: // right
                if (!ev.shiftKey && input.caret() == input.val().length) {
                  ev.preventDefault();
                  if (ev.altKey && This.options.editable) {
                    var row = input.closest('tr').prevAll().length;
                    if (input.closest("tbody").length) {
                      row++;
                    }
                    This.addcolumn();
                    This.element.find("tr:eq(" + row + ") td:last").trigger("click");
                  }
                  if (input.parent().nextAll("td").length) {
                    target = input.parent().next("td");
                    target.trigger("click");
                    input.blur();
                  }
                }
                break;
              case 9: // tab
                ev.preventDefault();
                var cell = $(this).parent()[0];
                var pos = $(this).prevAll("td").length;
                var set = This.element.find("td");
                if (This.options.sizeMode) {
                  set = set.not(":first");
                }
                set.each(function(i) {
                  if (this == cell) {
                    pos = i;
                    return false;
                  }
                });
                if (!ev.shiftKey) {
                  if (pos++ == set.length - 1) {
                    pos = 0;
                  }
                } else {
                  if (pos-- == 0) {
                    pos = set.length - 1;
                  }
                }
                set.eq(pos).trigger("click");
                $(this).blur();
                break;
              case 13: // enter
                ev.preventDefault();
                break;
            }
          });
        }
      } else {
        $(this).next("td").trigger('click');
      }
    },
    render: function() {
      this.element.empty();
      if (this.options.data.length) {
        for (var i = 0; i < this.options.data[0].entries.length; ++i) {
          this._calcMinWidth(i);
        }
        this._render();
      }
    },
    _render: function() {
      var This = this;
      var sets = this._calcColumnSets();
      for (var i = 0; i < sets.length; ++i) {
        var table = $(this.options.templates.table);
        this.element.append(table);
        var section;
        for (var j = 0; j < this.options.data.length; ++j) {
          if (this.options.data[j]._delete) {
            continue;
          }
          var row = $("<tr/>");
          if (!j) {
            section = $("<thead/>").appendTo(table);
            section.append(row);
            section = $("<tbody/>").appendTo(table);
          } else {
            section.append(row);
          }
          for (var k = 0; k < sets[i].cols.length; ++k) {
            if (j || k || !this.options.sizeMode) {
              var cell = $("<td>" + (this.options.data[j].entries[sets[i].cols[k]] || "&nbsp;") + "</td>");
              if (this.options.editable) {
                cell.click(this._clickCell);
              }
            } else {
              cell = $("<td/>");
            }
            row.append(cell);
            if (!k) {
              if (j && this.options.editable && this.options.data.length > 2) {
                var btn = $(this.options.templates.removeRowButton);
                btn.click(function(ev) {
                  ev.preventDefault();
                  var i = $(this).closest('tr').prevAll().length + 1;
                  //This.options.data.splice(i, 1);
                  This.options.data[i]._delete = true;
                  This.render();
                });
                cell.prepend(btn);
              }
              if (this.options.sizeMode) {
                cell.addClass("first");
              }
            }
          }
        }
        if (this.options.editable && this.options.data[0].entries.length > this.options.repeatFirstNColumns + 1) {
          var lastrow = $("<tr/>");
          table.append(lastrow);
          $.each(sets[i].cols, function(j) {
            var set = sets[i];
            btn = $(This.options.templates.removeColButton);
            if (j >= This.options.repeatFirstNColumns) {
              btn.find("a").click(function(ev) {
                ev.preventDefault();
                var index = set.cols[j];
                for (var k = 0; k < This.options.data.length; ++k) {
                  This.options.data[k].entries.splice(index, 1);
                }
                This.render();
              });
            } else {
              btn.empty();
            }
            lastrow.append(btn);
          });
        }
        if (sets[i].snap) {
          table.css("width", "");
        }
      }
      this.element.find("thead td:not(.first)").hover(
        function() {
          This.element.find(".hover").removeClass("hover");
          var i = $(this).prevAll().length;
          $(this).closest("table").find("tbody tr").find("td:eq(" + i + ")").addClass("hover");
        },
        function() {
          This.element.find(".hover").removeClass("hover");
        }
      );
      this.element.find("tbody tr").hover(
        function() {
          This.element.find(".hover").removeClass("hover");
          var i = $(this).prevAll().length;
          This.element.find("tbody").find("tr:eq(" + i + ")").find("td").addClass("hover");
        },
        function() {
          This.element.find(".hover").removeClass("hover");
        }
      );
    },
    addcolumn: function() {
      var rows = this.options.data.length;
      for (var i = 0; i < rows; i++) {
        this.options.data[i].entries.push("&nbsp;");
      }
      this.render();
    },
    addrow: function() {
      var cols = this.options.data[0].entries.length;
      var newrow = { entries: [] };
      for (var i = 0; i < cols; i++) {
        newrow.entries.push("&nbsp;");
      }
      this.options.data.push(newrow);
      this.render();
    },
    _setData: function(key, value) {
      this.options[key] = value;
      if ("disabled" == key) {
        this.element[value ? "addClass" : "removeClass"](this.widgetBaseClass + "-disabled " + this.namespace + "-state-disabled").attr("aria-disabled", value);
      } else if ("data" == key || "width" == key || "snapPoint" == key || "repeatFirstNColumns" == key || "sizeMode" == key) {
        this.render();
      }
    }
  });
  $.ui.sizechart.defaults = {
    data: [],
    width: 1000,
    snapPoint: 0.5,
    repeatFirstNColumns: 1,
    editable: false,
    sizeMode: true,
    widths: [],
    fudgeFactor: 8,
    testElement: null,
    templates: {
      removeColButton: "<td class='nobg'><a href='#' class='delcol'>x</a></td>",
      removeRowButton: "<a href='#' class='delrow'>x</a>",
      table: "<table style='width: auto;'/>"
    }
  };
})(jQuery);

(function($){$().ajaxSend(function(a,xhr,s){xhr.setRequestHeader("Accept","text/javascript, text/html, application/xml, text/xml, */*")})})(jQuery);(function($){$.fn.reset=function(){return this.each(function(){if(typeof this.reset=="function"||(typeof this.reset=="object"&&!this.reset.nodeType)){this.reset()}})};$.fn.enable=function(){return this.each(function(){this.disabled=false})};$.fn.disable=function(){return this.each(function(){this.disabled=true})}})(jQuery);(function($){$.extend({fieldEvent:function(el,obs){var field=el[0]||el,e="change";if(field.type=="radio"||field.type=="checkbox"){e="click"}else{if(obs&&field.type=="text"||field.type=="textarea"){e="keyup"}}return e}});$.fn.extend({delayedObserver:function(delay,callback){var el=$(this);if(typeof window.delayedObserverStack=="undefined"){window.delayedObserverStack=[]}if(typeof window.delayedObserverCallback=="undefined"){window.delayedObserverCallback=function(stackPos){observed=window.delayedObserverStack[stackPos];if(observed.timer){clearTimeout(observed.timer)}observed.timer=setTimeout(function(){observed.timer=null;observed.callback(observed.obj,observed.obj.formVal())},observed.delay*1000);observed.oldVal=observed.obj.formVal()}}window.delayedObserverStack.push({obj:el,timer:null,delay:delay,oldVal:el.formVal(),callback:callback});var stackPos=window.delayedObserverStack.length-1;if(el[0].tagName=="FORM"){$(":input",el).each(function(){var field=$(this);field.bind($.fieldEvent(field,delay),function(){observed=window.delayedObserverStack[stackPos];if(observed.obj.formVal()==observed.obj.oldVal){return}else{window.delayedObserverCallback(stackPos)}})})}else{el.bind($.fieldEvent(el,delay),function(){observed=window.delayedObserverStack[stackPos];if(observed.obj.formVal()==observed.obj.oldVal){return}else{window.delayedObserverCallback(stackPos)}})}},formVal:function(){var el=this[0];if(el.tagName=="FORM"){return this.serialize()}if(el.type=="checkbox"||self.type=="radio"){return this.filter("input:checked").val()||""}else{return this.val()}}})})(jQuery);(function($){$.fn.extend({visualEffect:function(o){e=o.replace(/\_(.)/g,function(m,l){return l.toUpperCase()});return eval("$(this)."+e+"()")},appear:function(speed,callback){return this.fadeIn(speed,callback)},blindDown:function(speed,callback){return this.show("blind",{direction:"vertical"},speed,callback)},blindUp:function(speed,callback){return this.hide("blind",{direction:"vertical"},speed,callback)},blindRight:function(speed,callback){return this.show("blind",{direction:"horizontal"},speed,callback)},blindLeft:function(speed,callback){this.hide("blind",{direction:"horizontal"},speed,callback);return this},dropOut:function(speed,callback){return this.hide("drop",{direction:"down"},speed,callback)},dropIn:function(speed,callback){return this.show("drop",{direction:"up"},speed,callback)},fade:function(speed,callback){return this.fadeOut(speed,callback)},fadeToggle:function(speed,callback){return this.animate({opacity:"toggle"},speed,callback)},fold:function(speed,callback){return this.hide("fold",{},speed,callback)},foldOut:function(speed,callback){return this.show("fold",{},speed,callback)},grow:function(speed,callback){return this.show("scale",{},speed,callback)},highlight:function(speed,callback){return this.show("highlight",{},speed,callback)},puff:function(speed,callback){return this.hide("puff",{},speed,callback)},pulsate:function(speed,callback){return this.show("pulsate",{},speed,callback)},shake:function(speed,callback){return this.show("shake",{},speed,callback)},shrink:function(speed,callback){return this.hide("scale",{},speed,callback)},squish:function(speed,callback){return this.hide("scale",{origin:["top","left"]},speed,callback)},slideUp:function(speed,callback){return this.hide("slide",{direction:"up"},speed,callback)},slideDown:function(speed,callback){return this.show("slide",{direction:"up"},speed,callback)},switchOff:function(speed,callback){return this.hide("clip",{},speed,callback)},switchOn:function(speed,callback){return this.show("clip",{},speed,callback)}})})(jQuery);
/*
    json2.js
    2008-01-17

    Public Domain

    No warranty expressed or implied. Use at your own risk.

    See http://www.JSON.org/js.html

    This file creates a global JSON object containing two methods:

        JSON.stringify(value, whitelist)
            value       any JavaScript value, usually an object or array.

            whitelist   an optional array parameter that determines how object
                        values are stringified.

            This method produces a JSON text from a JavaScript value.
            There are three possible ways to stringify an object, depending
            on the optional whitelist parameter.

            If an object has a toJSON method, then the toJSON() method will be
            called. The value returned from the toJSON method will be
            stringified.

            Otherwise, if the optional whitelist parameter is an array, then
            the elements of the array will be used to select members of the
            object for stringification.

            Otherwise, if there is no whitelist parameter, then all of the
            members of the object will be stringified.

            Values that do not have JSON representaions, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays will be replaced with null.
            JSON.stringify(undefined) returns undefined. Dates will be
            stringified as quoted ISO dates.

            Example:

            var text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'

        JSON.parse(text, filter)
            This method parses a JSON text to produce an object or
            array. It can throw a SyntaxError exception.

            The optional filter parameter is a function that can filter and
            transform the results. It receives each of the keys and values, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.

            Example:

            // Parse the text. If a key contains the string 'date' then
            // convert the value to a date.

            myData = JSON.parse(text, function (key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });

    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    Use your own copy. It is extremely unwise to load third party
    code into your pages.
*/

/*jslint evil: true */

/*global JSON */

/*members "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    charCodeAt, floor, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, length,
    parse, propertyIsEnumerable, prototype, push, replace, stringify, test,
    toJSON, toString
*/

if (!this.JSON) {

    JSON = function () {

        function f(n) {    // Format integers to have at least two digits.
            return n < 10 ? '0' + n : n;
        }

        Date.prototype.toJSON = function () {

// Eventually, this method will be based on the date.toISOString method.

            return this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z';
        };


        var m = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };

        function stringify(value, whitelist) {
            var a,          // The array holding the partial texts.
                i,          // The loop counter.
                k,          // The member key.
                l,          // Length.
                r = /["\\\x00-\x1f\x7f-\x9f]/g,
                v;          // The member value.

            switch (typeof value) {
            case 'string':

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe sequences.

                return r.test(value) ?
                    '"' + value.replace(r, function (a) {
                        var c = m[a];
                        if (c) {
                            return c;
                        }
                        c = a.charCodeAt();
                        return '\\u00' + Math.floor(c / 16).toString(16) +
                                                   (c % 16).toString(16);
                    }) + '"' :
                    '"' + value + '"';

            case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':
                return String(value);

            case 'object':

// Due to a specification blunder in ECMAScript,
// typeof null is 'object', so watch out for that case.

                if (!value) {
                    return 'null';
                }

// If the object has a toJSON method, call it, and stringify the result.

                if (typeof value.toJSON === 'function') {
                    return stringify(value.toJSON());
                }
                a = [];
                if (typeof value.length === 'number' &&
                        !(value.propertyIsEnumerable('length'))) {

// The object is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                    l = value.length;
                    for (i = 0; i < l; i += 1) {
                        a.push(stringify(value[i], whitelist) || 'null');
                    }

// Join all of the elements together and wrap them in brackets.

                    return '[' + a.join(',') + ']';
                }
                if (whitelist) {

// If a whitelist (array of keys) is provided, use it to select the components
// of the object.

                    l = whitelist.length;
                    for (i = 0; i < l; i += 1) {
                        k = whitelist[i];
                        if (typeof k === 'string') {
                            v = stringify(value[k], whitelist);
                            if (v) {
                                a.push(stringify(k) + ':' + v);
                            }
                        }
                    }
                } else {

// Otherwise, iterate through all of the keys in the object.

                    for (k in value) {
                        if (typeof k === 'string') {
                            v = stringify(value[k], whitelist);
                            if (v) {
                                a.push(stringify(k) + ':' + v);
                            }
                        }
                    }
                }

// Join all of the member texts together and wrap them in braces.

                return '{' + a.join(',') + '}';
            }
        }

        return {
            stringify: stringify,
            parse: function (text, filter) {
                var j;

                function walk(k, v) {
                    var i, n;
                    if (v && typeof v === 'object') {
                        for (i in v) {
                            if (Object.prototype.hasOwnProperty.apply(v, [i])) {
                                n = walk(i, v[i]);
                                if (n !== undefined) {
                                    v[i] = n;
                                }
                            }
                        }
                    }
                    return filter(k, v);
                }


// Parsing happens in three stages. In the first stage, we run the text against
// regular expressions that look for non-JSON patterns. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we want to reject all
// unexpected forms.

// We split the first stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace all backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

                if (/^[\],:{}\s]*$/.test(text.replace(/\\./g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the second stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                    j = eval('(' + text + ')');

// In the optional third stage, we recursively walk the new structure, passing
// each name/value pair to a filter function for possible transformation.

                    return typeof filter === 'function' ? walk('', j) : j;
                }

// If the text is not JSON parseable, then a SyntaxError is thrown.

                throw new SyntaxError('parseJSON');
            }
        };
    }();
}

/* LOG
SUMMARY: Log is a convenience frontend for the firebug console.
DESCRIPTION: Log will automatically hierarchically group output by the function that
  called it, and compute total time spent in each group.  Log has lots of settings and
  is very flexible.  By default, Log writes to console.debug.  The first call to log()
  in any function will be output using console.group
SETTINGS:
  log.data.enable=false -- global on/off, enables all logging, not just from log.setup
  log.data.time=true -- enables displaying time spent in each log group
  log.data.delay=1000 -- stop logging after this # of ms w/out a call to log
METHODS:
  log(["func",]...) -- outputs arguments to console.  if the first argument is the name
             of a console function, that function will be called instead of the default.
  log.enable() -- global enable, or just add "all" to the log query string parameter
  log.setup([sets]) -- if test is null or true or a string value set using the log query
             string parameter, will temporarily turn on logging for this function.
  log.stop() -- stops logging this function.  Has no effect if global logging is enabled
  log.stopAll() -- stops all logging.  Has no effect if global logging is enabled
  log.trace() -- safe call to console.trace
  log.debug(), log.info(), log.warn(), log.error() -- aliases to log("func",...)
AUTHOR: Kevan Davis on 29 APR 2009
KNOWN ISSUES:
  #1 If using collapsed grouping, the order the groups are render is sometimes incorrect
       this is a fire bug issue (http://code.google.com/p/fbug/issues/detail?id=1676)
  #2 If the top group does not have an explicit stop() at the end, the final time is too
       long, by approximately the length of the delay (default: 1 second)
*/

if ("undefined" == typeof log) {
  try {
    this.log = function() {
      if (!(log.data.enabled || log.caller.logThis) || "undefined" == typeof console) {
        return log;
      }
      clearTimeout(log.data.autoclosetimeout);
      if (-1 == log.data.closetocurrent()) {
        var args = arguments;
        if (log.data.calcuniques) {
          args = [].splice.call(arguments, 0);
          args.push(" (Key: " + log.caller.uniqueKey + ")");
        }
        try {
          if ("function" == typeof console[arguments[0]]) {
            log.data.group.apply(null, [].splice.call(args, 1));
          } else {
            log.data.group.apply(null, args);
          }
        } catch(_) { log.data.out(args); }
        if (log.caller.profileThis && !log.data.profiling) {
          try { console.profile(); } catch(_) {}
          log.data.profiling = true;
        }
        if (log.data.time) {
          try { console.time("" + log.data.callstack.length); } catch(_) {}
        }
        log.data.callstack.push(log.caller);
      } else {
        log.data.out(arguments);
      }
      log.data.autoclosetimeout = setTimeout(log.data.autoclosefunc, log.data.delay);
      return log;
    };
    log.data = {
      message: console.debug || console.info || console.warn || console.error, //not all browsers are equal.  if console is not defined (IE), will fail here, and be caught below
      out: function( args ){
        try {
          if ("function" == typeof console[ args[0] ]) {
            try {
              console[ args[0] ].apply(null, [].splice.call(args, 1));
            } catch(_) { console[ args[0] ]( [].splice.call(args, 1)); }
          } else {
            try { log.data.message.apply(null, args); } catch(_) { log.data.message(args); }
          }
        } catch(chromeFubar) { try { console.info(args); } catch(_) {} }
      },
      group: /*console.groupCollapsed||*/console.group, // groupCollapsed is an experimental feature;  use with caution
      calcuniques: false,
      enabled:     false,
      enableList:  [],
      profileList: [],
      profiling:   false,
      time:        true,
      callstack:   [],
      delay:       1000,
      autoclosetimeout: null,
      regex: {
        newline: /\n/g,
        slash:   /\//,
        colon:   /:/,
        js:      /\.js/
      },
      autoclosefunc: function() {
        clearTimeout(log.data.autoclosetimeout);
        var closeIndex = log.data.callstack.length - 1;
        while (0 <= closeIndex--) {
          if (log.data.time) {
            try { console.timeEnd("" + closeIndex); } catch (_) {}
          }
          try{ console.groupEnd(); } catch(_) {}
          log.data.callstack.pop();
        }
        if (log.data.profiling) {
          try { console.profileEnd(); } catch (_) {}
        }
        log.data.profiling = false;
        return log;
      },
      closetocurrent: function() {
        var nca = arguments.callee.caller.caller,//nearest common ancestor
            index = log.data.inArray(nca, log.data.callstack);
        if (log.data.callstack.length && index != log.data.callstack.length - 1) {
          try {
            while (nca && -1 == log.data.inArray(nca, log.data.callstack))
              nca = nca.caller;
          } catch (_) {}; // occasionally happens, if an ajax error is raised (500 error?)
          if ( nca ) {
            while (log.data.callstack.length && log.data.callstack[ log.data.callstack.length - 1 ] != nca) {
              if (log.data.time) {
                try { console.timeEnd("" + (log.data.callstack.length - 1)); } catch (_) {}
              }
              try { console.groupEnd(); } catch(_) {}
              log.data.callstack.pop();
            }
          }
        }
        return index;
      },
      inArray: function(elem, array) {
        var i=array.length;
        while (i--){
          if (array[i] === elem) {
            return i;
          }
        }
        return -1;
      },
      prepend: function(msg, args) {
        args = [].splice.call(args, 0);
        args.unshift(msg);
        return args;
      }
    };
    log.setup = function() {
      if (!log.data.profileList.length && (log.data.enabled || !log.data.enableList.length)) { // skip if no logging is enabled
        return log;
      }
      var f = arguments.callee.caller;
      if ("undefined" == typeof f.logThis) { // only execute once
        f.logThis = (true === arguments[0]);
        f.profileThis = false;
        var args = arguments;
        if (log.data.calcuniques) { // this block substantially increases time spent in this function, approx 100x
          try { (0)(); } catch (e) { // cause an exception so we can get the raw stacktrace
            try { // this method only works in firefox
              var r = log.data.regex; // to save on lookups
              var caller = e.stack.split(r.newline)[1].split(r.slash);
              caller = caller[ caller.length - 1 ].split(r.colon);
              f.uniqueKey = "f_" + caller[0].split(r.js)[0] + caller[1];
              args = [].splice.call(arguments, 0);
              args.push(f.uniqueKey);
            } catch(_) {}
          }
        }
        if ("string" == typeof args[0]) {
          var p = args.length;
          while (p-- && !(f.profileThis && f.logThis)) {
            if (-1 != log.data.inArray(args[p], log.data.profileList)) {
              f.profileThis = f.logThis = true;
            } else if (-1 != log.data.inArray(args[p], log.data.enableList)) {
              f.logThis = true;
            }
          }
        }
      }
      return log;
    };
    log.stop = function() {
      log.data.closetocurrent();
      if (1 == log.data.callstack.length) {
        log.data.autoclosefunc();
      }
      return log;
    };
    log.stopAll = log.data.autoclosefunc;
    log.enable = function() { log.data.enabled = true; return log; };//to global enable at startup
    log.debug  = function() { return log.apply(null, log.data.prepend("debug", arguments)); }; // don't use these 4 for now, they don't group properly
    log.info   = function() { return log.apply(null, log.data.prepend("info",  arguments)); };
    log.warn   = function() { return log.apply(null, log.data.prepend("warn",  arguments)); };
    log.error  = function() { return log.apply(null, log.data.prepend("error", arguments)); };
    log.trace  = function() { try { console.trace(); } catch(_) {} return log; }; // just a convenience
  } catch(_) {
    // Placeholders so no errors are raised about missing methods or properties
    log = function() { return log; };
    log.data = { enableList: [], profileList: [], callstack: [] }; //only those vars that ppl might try to dereference
    log.setup = log.stop = log.stopAll = log.enable = log.info = log.warn = log.error = log.trace = function() { return log; };//only public functions
  }
  try {
    var raw_log = document.location.search.match(/log=([^&]*)?/);
    if (raw_log) { log.data.enableList = raw_log[1].split(","); }
    if ( -1 != log.data.inArray("all", log.data.enableList)) {
      log.enable();
    }
  } catch(_) {}
  try {
    var raw_profile = document.location.search.match(/log2=([^&]*)?/);
    if (raw_profile) { log.data.profileList = raw_profile[1].split(","); }
  } catch(_) {}
  try {
    log.data.calcuniques = (document.location.search.match( /loguniques/ ) ||
                            document.location.search.match( /log?.*(?=[=,]f_)/));
  } catch(_) {}
  if (!log.data.enabled && !log.data.enableList.length && !log.data.profileList.length) {
    // No logging is enabled, kill Log, TODO: optimize this opt out, so log doesn't get created in the first place
    log = function() { return log; };
    log.data = { enableList: [], profileList: [], callstack: [] }; //only those vars that ppl might try to dereference
    log.setup = log.stop = log.stopAll = log.enable = log.info = log.warn = log.error = log.trace = function() { return log; };//only public functions
  }
}
// END LOG

var Locale = {
    validation_field_required_text: 'This field is required.',
    validation_not_valid: '&quot; does not appear to be valid.',
    validation_email_address: 'Email address &quot;',
    bounce_message: 'Please note that we are unable to send emails to you. Please verify that your inbox is not full and that your email address is correct.<br/>To continue to receive email from Gilt Groupe, please ',
    click_here: 'click here',
    please_wait: "Please wait",
    please_wait_loading: 'Please wait. Loading...',
    please_wait_loading_spin: '<div id="MB_loading">Please wait. Loading...</div>',
    close_window: 'Close window',
    your_cart: 'Your Cart',
    your_wait_list: 'Your Wait List',
    please_select: function(msg) { return 'Please select ' + msg; },
    select_color: 'Select Color:',
    color: 'Color',
    size: 'Size',
    Sizing: "Sizing",
    conjunct: ' and ',
    minutes: ' minutes',
    blackbird_form_error: 'There was an error processing your registration. Please verify the information on the form.',
    is_out_of_stock: function (label) { return label + ' is out of stock.'; },
    add_to_cart_now_sold_out: 'Sorry, this item is now Sold Out.',
    is_not_available: 'This item is not available because it&rsquo;s in another member&rsquo;s cart. The item may become available if the member decides not to purchase it.',
    wait_list_unavailable: 'We\'re sorry, the wait list is currently unavailable.',
    wait_list_success: function(product) { return product + ' has been added to your Wait List'; },
    max_cart_size: function(max) { return 'You can only add ' + max + ' items to your cart at a time'; },
    loading: 'Loading...',
    n_units: function(n, sku_label) { return 'We only had ' + n + ' of the ' + sku_label + ' in stock.  Your cart has been adjusted to reflect our remaining inventory.'; },
    others_may_purchase_this_item: '<span class="label expired">This item is no longer reserved.</span>',
    others_may_purchase_these_items: '<br/>These items are no longer reserved. Other members may purchase them.',
    this_item_reserved: function(seconds) { return '<span class="brand' + (120 > seconds ? ' expiring' : '') + '"><span class="countdown">' + fl.Util.secondsToMinutesSeconds(seconds) + '</span> minutes.</label>'; },
    these_items_reserved: function(seconds) { return '<br/>These items are reserved for the next <span class="countdown">' + fl.Util.secondsToMinutesSeconds(seconds) + '</span> minutes.'; },
    currency_symbol: '$',
    currency_group_delimiter: ',',
    currency_decimal_point: '.',
    shipping_address_street_length_message: function(length) { return 'We limit the length of each address line to ' + length + ' characters to ensure the entire address prints on the shipping label.'; },
    textarea_length_message: function(length) { return 'You can enter at most ' + length + ' characters in this field.'; },
    validation_postal_code: 'US postal code must contain exactly 5 digits (e.g. 10011) or 9 digits (e.g. 10011-4318)',
    all: "All",
    you_are_leaving_gilt_title: "Before you leave Gilt",
    you_are_leaving_fuse_title: "Before you leave Gilt Fuse",
    you_are_leaving_gilt_for_fuse_message: function(msg, checkoutLink, checkoutEvent, proceedLink) {
      var numItems = gg.Cart.current.quantity || gg.Cart.current.reservations.length;
      var checkoutEventOnclick = '';
      if (checkoutEvent && checkoutEvent != "") {
        checkoutEventOnclick = "onclick='" + checkoutEvent + "' "
      }
      return "<h2>You have " + numItems + " item" + (numItems > 1 ? "s" : "") + " in your Gilt Cart " + msg + "</h2>" +
             "<p>For now, Gilt and Gilt Fuse maintain <strong>separate carts</strong>. To avoid losing your items, we recommend you <a href='" + checkoutLink + "'>check out now.</a></p>" +
             "<p>Remember, we offer free shipping on any additional orders placed on Gilt and Gilt Fuse within one hour.</p>" +
             "<div class='actions'><a href='" + checkoutLink + "' class='checkoutnow' " + checkoutEventOnclick +
              ">Check Out Now</a><a href='" + proceedLink + "' class='proceed'>Proceed</a></div><br style='clear:both' />";
    },
    you_are_leaving_fuse_for_gilt_message: function(msg, checkoutLink, checkoutEvent, proceedLink) {
      var numItems = gg.Cart.current.quantity || gg.Cart.current.reservations.length;
      var checkoutEventOnclick = '';
      if (checkoutEvent && checkoutEvent != "") {
        checkoutEventOnclick = "onclick='" + checkoutEvent + "' "
      }
      return "<h2>You have " + numItems + " item" + (numItems > 1 ? "s" : "") + " in your Fuse Cart " + msg + "</h2>" +
             "<p>For now, Gilt Fuse and Gilt maintain <strong>separate carts</strong>. To avoid losing your items, we recommend you <a href='" + checkoutLink + "'>check out now.</a></p>" +
             "<p>Remember, we offer free shipping on any additional orders placed on Gilt Fuse and Gilt within one hour.</p>" +
             "<div class='actions'><a href='" + checkoutLink + "' class='checkoutnow' " + checkoutEventOnclick +
             ">Check Out Now</a><a href='" + proceedLink + "' class='proceed'>Proceed</a></div><br style='clear:both' />";
    },
    you_are_leaving_subsite_expirationcase: function(seconds) { return 'reserved for the next <span class="highlight"><span class="countdown">' + fl.Util.secondsToMinutesSeconds(seconds) + '</span> minutes</span>'; },
    shipping_exemption_dialog_title: "Products Cannot be Shipped to this Address",
    gift_card: "Gilt e-Gift Card",
    please_select_a_credit_card: "Please select a credit card",
    field_does_not_match_address_provided: function(field, value) { return field + " does not match address provided (" + value + " suggested)"; },
    address_verification_provider_error: function(code, other) { 
      switch(code) {
        case 'M': return "Could not identify your exact address as there were multiple potential matching addresses";
        case 'N': return "Could not confirm that the street name you entered exists in the zip code entered";
        case 'R': return "The house number you entered appears to be out of range for the street you entered";
        case 'U': return "Could not confirm the name of your street. Please double check that the city, state, zip code and house number are correct.";
        case 'X': return "The address you entered is listed as non deliverable";
        case 'Z': return "The zip code you entered does not match the city and state";
        default:  return "Address verification error: " + other;
      }
    }
};

$(function() {
    try {
        $.extend($.validator.messages, {
            email: function(_, el) { return "Email address does not appear to be valid."; }
        });
    } catch(_) {
        setTimeout(arguments.callee, 100);
    }
    var gg;
    if (gg) {
      gg.newProductFilter.filterTypes.category.displayPrefix = ["Category", "Categories"];
      gg.newProductFilter.filterTypes.size.displayPrefix = ["Size", "Sizes"];
    }
});

// Copyright 2007-2008 Gilt Groupe, Inc.

var gg;
if (!gg) {
    gg = {};
}


if (!gg.Admin) {
    gg.Admin = { _isAdmin: false };
}

gg.Admin.setIsAdminPage = function(isAdmin) {
    gg.Admin._isAdmin = isAdmin;
};

gg.Admin.isAdminPage = function() {
    return gg.Admin._isAdmin;
};


if (!gg.Site) {
    gg.Site = {};
}
gg.Site.currentSubsite = {};

// Prevents a function from executing again if it has already executed within a threshold
// Use 'id' to keep functions which should be throttled from stepping on each other.
gg._functionThrottle = {};
gg.throttleFunction = function(id, func, threshold) {
    return function(event) {
        var now = new Date().getTime();
        var last = gg._functionThrottle[id];
        if (!last || now > last + (threshold || 100)) {
            gg._functionThrottle[id] = now;
            return (func)(event);
        }
        if (event) {
            event.preventDefault();
        }
        return false;
    };
};

gg._formThrottle = {};
gg.throttleFormSubmit = function() {
    for (var i = 0, len = document.forms.length; i < len; ++i) {
        var form = document.forms[i];
        var id = form.id || ('form_' + Math.floor(Math.random()*1000000));
        if (gg._formThrottle[id]) {
            // don't install it twice on the same form -- might happen with ajax updates.
            return;
        }
        gg._formThrottle[id] = 1;
        jQuery(form).bind('submit', function(event) {
            var now = new Date().getTime();
            var last = gg._formThrottle[id] || 1;
            if (now > last + 1000) {
                gg._formThrottle[id] = now;
                // let event go ahead.
            }
            else {
                event.preventDefault();
                return false;
            }
            return true;
        });
    }
};

gg.cookieUpdate = {};

gg.cookieUpdate.updateCACookie = function() {
    if (!fl.Util.readCookie('ca_expiration')) {
        $.get('/ajax/update_ca_cookie', null, function(data) {
            if ('0' != data) {
                // Cookies have been updated. check if we can
                // redirect, but be very conservative. We only
                // care to redirect the /sale urls - if there are
                // no query parameters, we redirect
                var url = window.location.toString();
                if (-1 == url.indexOf('?') && -1 != url.indexOf('/sale')) {
                    window.location = url + '?ucac=1';
                }
            }
        }, 'text');
    }
};


if (!gg.FixIE) {
    gg.FixIE = {};
}

gg.FixIE.PngToGif = function() { // Deprecated
    var trans_png_exp = /\-trans.png/i;
    $('.trans').each(function(_,e) {
        if (e.src && trans_png_exp.test(e.src)) {
            e.src = e.src.replace(/\.png/,'.gif');
        }
    });
};

gg.FixIE.Sprites = function() {
  $("a.sprite").each(function() {
    var sizingClone = $(this).clone();
    sizingClone.appendTo("body");
    $(this).css({ width: sizingClone.width() });
    sizingClone.remove();
  }).filter("a.sprite-scalable")
      .hover(function(){
        if ($(this).hasClass("sprite-scalable-nodownstate")) {
          $(this).addClass("sprite-scalable-nodownstate-hover");
        } else {
          $(this).addClass("sprite-scalable-hover");
        }
      }, function() {
        $(this)
          .removeClass("sprite-scalable-nodownstate-hover")
          .removeClass("sprite-scalable-hover");
      })
      .mousedown(function() {
        if ($(this).hasClass("sprite-scalable-nodownstate")) {
          $(this).addClass("sprite-scalable-nodownstate-active");
        } else {
          $(this).addClass("sprite-scalable-active");
        }
      })
      .mouseup(function() {
        $(this)
          .removeClass("sprite-scalable-nodownstate-active")
          .removeClass("sprite-scalable-active");
      });
};

if (!gg.FlashMessage) {
    gg.FlashMessage = {};
}

gg.FlashMessage.init = function () {
    log.setup("startup", "gg")("Initializing Flash Message");
    var flash_cookie = fl.Util.readCookie('flash');
    log("Flash Cookie:", flash_cookie);
    if (flash_cookie) {
        var flash_message = gg.parse_json(flash_cookie);
        fl.Util.expireCookie('flash');
        if (flash_message.notice) {
            var flash_message_div = $('#flash_message');
            if (flash_message_div) {
                flash_message_div.append(flash_message.notice);
                flash_message_div.show();
            }
        }
    }
};

if (!gg.Sprite) {
    gg.Sprite = {};
}

gg.Sprite.init = function() {
    log.setup("startup", "gg", "sprite")("Initializing Sprites");
    var sprites = $('a[sprite_offset], input[sprite_offset]');
    var i = sprites.length;
    while (i--) {
        gg.Sprite.enableSprite(sprites.eq(i));
    }
};

gg.Sprite.enableSprite = function(sprite) {
    if (fl.Util.isInitialized('Sprite', sprite)) {
        return;
    }
    log.setup("startup", "gg", "sprite")("Enabling Sprite #%o", sprite);
    sprite.html('');
    var offset = sprite.attr('sprite_offset');
    sprite.hover(
        function() {
            log.setup("interaction", "gg", "sprite")("Sprite #%o move %dpx", sprite, offset);
            sprite.css({ backgroundPosition: '0 -' + offset + 'px' });
        },
        function() {
            log.setup("interaction", "gg", "sprite")("Sprite #%o reset", sprite);
            sprite.css({ backgroundPosition: '0 0' });
        }
    );
};

if (!gg.Tracking) {
    gg.Tracking = {};
}
if (!gg.Tracking.Google) {
    gg.Tracking.Google = {};
}

gg.Tracking.Google.Init = function () { // Why set constant data in a function?
    gg.Tracking.Google.config = {
        vendor_id: 'K187348'
    };
};

gg.Tracking.Google.setActionTag = function() {
    var data = fl.Util.readCookie('blackbird_user_data');
    var hash = "";
    if (data) {
        hash = data.split('_')[0];
    }
    var img_tag = $.format('<img width="1" height="1" src="https://clickserve.cc-dt.com/link/action?oid=ccdt_{0}&amp;vid={1}" id="ga_action_tag" alt="" style="display: none;"/>', hash, gg.Tracking.Google.config.vendor_id);
    $("#footer").append(img_tag);
};

if (!gg.Tracking.Google.AdWords) {
    gg.Tracking.Google.AdWords = {};
    gg.Tracking.Google.AdWords.script = 'http://www.googleadservices.com/pagead/conversion.js';
}

gg.Tracking.Google.AdWords.sendTagRequest = function(conversion_id, format, color, label, conversion_value) {
  $(function() {
    var google_conversion_id = conversion_id;
    var google_conversion_language = 'en_US';
    var google_conversion_format = format;
    var google_conversion_color = color;
    var google_conversion_label = label;
    if (conversion_value) {
      var google_conversion_value = conversion_value;
    }
    try {
      $.getScript(gg.Tracking.Google.AdWords.script);
    } catch (err) {
      // TODO: log error
    }
  });
}

if (!gg.Validation) {
    gg.Validation = {};
}

gg.Validation.disable = function() {
   /* var el = $('#user_first_name');
    el.unbind('blur', el.data("validate_required"));*/
};

gg.Validation.enable = function() {
    /*var el = $('#user_first_name');
    el.data("validate_required", function() {
        fl.Validate.Required(el);
    });
    el.blur(el.data("validate_required"));*/
};

// Add authentication token to certain links (like iCal and RSS links).
// To add the user's login key to any link just add the 'lk' class to it.
gg.processLoginKey = function() {
    log.setup("startup", "gg")("Appending login key to links");
    var data = gg.Usermeta.data();
    var login_key = null;

    if (data && data.login_key) {
        login_key = data.login_key;
    }

    var keys = $ ('.lk');
    var i = keys.length;
    while (i--) {
        var el = keys.eq(i);
        if (el.attr('href')) {
            if (!login_key) {
                el.attr("href", '/ajax/update_usermeta_cookie/?return_url=' + encodeURIComponent(el.attr("href")));
            } else {
                log("Appending login key to %s", el.attr("href"));
                if (-1 == el.attr("href").indexOf('?')) {
                    el.attr("href", el.attr("href") + '?k=' + login_key);
                } else {
                    el.attr("href", el.attr("href") + '&k=' + login_key);
                }
            }
        }
    }
};

gg.site_feedback_set_loading = function(id) {
    $("#" + id).html('<div id="MB_loading">Submitting Feedback...</div>');
};

gg.to_json = function(value) {
    return JSON.stringify(value);
};

gg.parse_json = function(value) {
    if (!value) {
        return null;
    }
    if ("object" == typeof value) {
        return value;
    }
    // hack to unescape spaces...unescape and unescapeURI only handle %20 and JSON.parse doesn't do it
    value = value.replace(gg.parse_json.strip, ' ');
    return JSON.parse(value);
};
gg.parse_json.strip = /[\+\n\r]/g;

gg.random_string = function(string_length, hex_only) {
    var randomstring = '';
    var i = string_length;
    while (i--) {
        if (!hex_only) {
            var ccode = Math.floor(Math.random() * 62) + 48; // 0-9
            if (57 < ccode) {                                // A-Z
                ccode += 7;
            }
            if (90 < ccode) {                                // a-z
                ccode += 6;
            }
        } else {
            ccode = Math.floor(Math.random() * 16) + 48; // 0-9
            if (57 < ccode) {
                ccode += 39;                             // a-f
            }
        }
        randomstring += String.fromCharCode(ccode);
    }
    return randomstring;
};

if (!gg.History) {
  gg.History = {};
}

gg.History.back = function(url) {
  if (history.length > 1) {
    history.back();
  } else if (url != null) {
    window.location = url;
  }
};

// Copyright 2007-2008 Gilt Groupe, Inc.
var fl;
if (!fl) {
    fl = {};
}
var Gilt;
if (!Gilt) {
  Gilt = {};
}

fl.Init = {};
fl.Init.is_initialized = false;
fl.Init.scms_version_id = null;
fl.Init.question_mark_regexp = null;
fl.Init.ImageUri = function(uri) { // why?
    return uri;
};

// cdnUri: The full path to the domain hosting our images (e.g. http://cdn.gilt.com)
// versionKey: Appended to every cdn image query via javascript. This should be the
//    most recent mtime of ALL assets we may serve from the CDN
fl.Init.WindowLoad = function(cdnUri, versionKey, scmsVersionId) {
    log.setup("startup", "fl")("Loading...");
    fl.Init.scms_version_id = scmsVersionId;

    if (!fl.Init.question_mark_regexp) {
        fl.Init.question_mark_regexp = new RegExp(/\?j_/);
    }

    if (cdnUri) {
        fl.Init.ImageUri = function(uri) {
            if ( fl.Init.question_mark_regexp.test(cdnUri) )  {
                return cdnUri;
            }
            return cdnUri + uri + '?j_' + versionKey;
        };
    } else if (versionKey) {
        fl.Init.ImageUri = function(uri) {
            if ( fl.Init.question_mark_regexp.test(cdnUri) )  {
                return uri;
            }
            return uri + '?j_' + versionKey;
        };
    }
    fl.Init.Initialize();
    fl.Init.is_initialized = true;
    log.stopAll();
};
// Can be called multiple times per page if the page uses ajax. For
// example, a form brought in via ajax will need to make sure this
// function is called to setup all of our validation on the form.
// This function should not have any parameters.
fl.Init.Initialize = function() {
    log.setup("startup", "fl")("Initializing Gilt Groupe");
    gg.Usermeta.init();
    gg.throttleFormSubmit();
    fl.ImageSubmit.init();
    fl.ImageRollover.init();
    fl.ToolTip.init();
    fl.Form.init();
    fl.Form.autoFocusForms();
    if (!gg.Admin.isAdminPage()) {
        // On admin, let rails validate forms.
        fl.Validate.AutoInit();
    }
    gg.Sprite.init();
    gg.processLoginKey();
    gg.FlashMessage.init();
    Gilt.SingleSignOnLinks.init();
    log("Initialization Complete").stop();
};
fl.Init.isInitialized = function() {
    return fl.Init.is_initialized;
};

fl.ImageSubmit = {};
// Looks for input type=image and downloads the images. We do this to
// get these particular images to download as quickly as possible
fl.ImageSubmit.init = function() {
    log.setup("startup", "fl")("Initializing Image Submit");
    var inputs = $('input[type=image]');
    var i = inputs.length;
    var el;
    while (el = inputs[--i]) {
        if (fl.Util.isInitialized('ImageSubmitInit', el)) {
            continue;
        }
        log.setup("startup", "fl")("Preloading %s", el.attr("src"));
        (new Image()).src = el.attr("src");
    }
    log("Image Submit Initialization Complete");
};
fl.ImageRollover = {};
fl.ImageRollover.useZoomEffect = false;
fl.ImageRollover.init = function() {
    log.setup("startup")("Initializing Image Rollovers");

    $("img[rollover]").rollover({
        rollover_source: "rollover",
        otherrollover_sources: "rollover_associated_ids",
        otherrollover_targets: "rollover_associated_urls"
    });

    var imgs = $(".zoom img");
    var i = imgs.length;
    while (i--) {
        imgs.eq(i).attr("fullsrc", imgs.eq(i).attr("src").replace(/\/sm\./,"/lg."));
    }
    if (fl.ImageRollover.useZoomEffect) {
      imgs.zoom({
        container: $("#photoZoom"),
        triggerEvent: "zoomstart", // custom event, so we can do some other stuff first
        useZoomInEffect: false,
        useZoomOutEffect: false,
        panSpeed: 0,
        easing: "linear"
        // All options, for demo:
        /*easing: (-1 != document.location.search.search(/[&\?]paneasing=(\w*)/)) ? document.location.search.match(/[&\?]paneasing=(\w*)/)[1] : "swing",
        panSpeed: (-1 != document.location.search.search(/[&\?]panspeed=(\d*|\w*)/)) ? parseInt(document.location.search.match(/[&\?]panspeed=(\d*)/)[1])||document.location.search.match(/[&\?]panspeed=(\w*)/)[1] : "fast",
        zoomSpeed: (-1 != document.location.search.search(/[&\?]zoominspeed=(\d*|\w*)/)) ? parseInt(document.location.search.match(/[&\?]zoominspeed=(\d*)/)[1])||document.location.search.match(/[&\?]zoominspeed=(\w*)/)[1] : "slow",
        resetSpeed: (-1 != document.location.search.search(/[&\?]zoomoutspeed=(\d*|\w*)/)) ? parseInt(document.location.search.match(/[&\?]zoomoutspeed=(\d*)/)[1])||document.location.search.match(/[&\?]zoomoutspeed=(\w*)/)[1] : "fast",
        useZoomInEffect: -1 == document.location.search.search(/[&\?]zoomin=(false)/),
        useZoomOutEffect: -1 == document.location.search.search(/[&\?]zoomout=(false)/)*/
      });
    }

    log("Image Rollover Initialization Complete");
};

fl.Form = {};
// Places focus on first non empty input field
// $(function() { fl.Form.focusFirstEmptyField('loginform'); });
fl.Form.focusFirstEmptyField = function(formId) {
    var input = $("#" + formId + " input:not(:hidden):blank:first");
    if (input.length) {
        input.focus();
    } else {
        $("#" + formId + " input:not(:hidden):first").focus();
    }
};
fl.Form.initChangeButtonOnSubmit = function() {
    log.setup("startup", "form")("Initializing Change Button On Submit Event");

    var forms = $(".autoChange:image").closest("form");
    if (forms.length) {
        $("<img/>").attr("src", '/images/default/buttons/please_wait.gif'); // TODO: this should be a constant
        var f = function() {
            log.setup("interaction", "form")("Changing Button on Submit");
            var img = $(this).find(".autoChange:image"); // I'm assuming there's only 1
            img.data("oldSrc", img.attr("src"))
               .attr("src", '/images/default/buttons/please_wait.gif');
            this.disable();
        };
        forms.unbind("submit", f).submit(f);
    }
};
fl.Form.enable = function() {
    var inputs = $('.autoChange:image');
    var i = inputs.length;
    if (i) {
        while (--i) {
            var el = inputs.eq(i);
            if (el.data("oldSrc")) {
                el.attr("src", el.data("oldSrc"))
                  .removeData("oldSrc")
                  .closest("form")
                    .get().enable();
            }
        }
    }
};
// To focus first input element of a form:
// <% form_tag url_for(:action =>  'update'), :class => 'autoFocus' do -%>
// To focus first empty input element of a form:
// <% form_tag url_for(:action =>  'update'), :class => 'autoFocusEmpty' do -%>
fl.Form.autoFocusForms = function() {
    log.setup("startup", "fl", "form")("Autofocusing on Form");
    var forms = $('form');
    var i = -1;
    var max = forms.length;
    while (++i < max) {
        var el = forms.eq(i);
        if (el.hasClass('autoFocus')) {
            log("Focusing on first field");
            el.find("input[type!=hidden]:first").focus();
            return;
        } else if (el.hasClass('autoFocusEmpty')) {
            log("Focusing on first empty field");
            fl.Util.MaybeAssignID(el);
            fl.Form.focusFirstEmptyField(el.id());
            return;
        }
    }
};
// Auto disable the submit button until all inputs have data.
// If you do not pass in the ID of the submit tag, we'll disable the
// first one we find in the form (first image or submit input tag)
// $(function() { fl.Form.autoDisableSubmit('loginform', 'submit'); });
fl.Form.autoDisableSubmit = function(formId, submitId) {
    log.setup("startup", "fl", "form")("Disabling form submit for form #%s", formId);
    if (!submitId) {
        var form = $("#" + formId);
        if (!form) {
            return;
        }
        var el = form.find(":image, :submit").eq(0);
        if (!el.id()){
            el.id('_fl_autoDisableSubmit');
        }
        submitId = el.id();
    }

    fl.Form.autoDisableSubmitCheck(formId, submitId);
    var inputs = $("#" + formId + " :input");
    var i = inputs.length;
    var f = function() {
        fl.Form.autoDisableSubmitCheck(formId, submitId);
    };
    while (i--) {
        inputs.eq(i).blur(f);
    }

    // Also observe the form so you don't have to tab out of a final text box
    log("Attaching a Form Observer");
    /*new Form.Observer(formId, 0.5, function(_, value) { // TODO: jquery equivalent, probably a plugin
        var map = value.toQueryParams();
        var filled_out = true;
        for (var key in map) {
            if (map.hasOwnProperty(key) && !map[key]) {
                filled_out = false;
                return;
            }
        }
        if (filled_out) {
            fl.Form.autoDisableSubmitCheck(formId, submitId);
        }
    });*/
};
fl.Form.autoDisableSubmitCheck = function(formId, submitId) {
    log.setup("interaction", "fl", "form")("Checking for missing data");
    var inputs = $("#" + formId + " :input");
    var i = inputs.length;
    while (i--) {
        if (!inputs.eq(i).val()) {
            log("Missing data found, disabling submit");
            $("#" + submitId).attr("disabled","disabled");
            return;
        }
    }
    log("No missing data found, enabling submit");
    $("#" + submitId).attr("disabled","");
};
fl.Form.init = function() {
    log.setup("startup", "fl", "form")("Initializing Forms");
    fl.Form.initPreviewText();
    fl.Form.initChangeButtonOnSubmit();
    fl.Form.initOnKeyPress();
    fl.Form.initPhoneNumberFields();
    fl.Form.usermetaPrefillEmail();
    log("Forms Initialization Complete");
};

fl.Form.initPhoneNumberFields = function() {
    log.setup("startup", "fl", "form")("Adding Phone Number Formatters");
    var inputs = $('input[type=text]');
    var i = inputs.length;
    var el;
    var f = function(el) {
        return function() {
            fl.Formatter.phone(el);
        };
    };
    while (--i > -1) {
        el = inputs.eq(i);
        if (el.hasClass('phone_number')) {
            fl.Formatter.phone(el);
            el.blur(f(el));
        }
    }
};

// looks for test field inputs with class user_prefill_email, and
// prefills the box with the contents from a cookie named email, if set
fl.Form.usermetaPrefillEmail = function() {
    if (-1 != window.location.toString().indexOf('noemail=')) {
        return;
    }

    var cookie_value = fl.Util.readCookie('email');
    if (!cookie_value) {
        return;
    }
    log.setup("startup", "fl", "form")("Adding detected email address %s to all email fields", cookie_value);
    if (!$("input.usermeta_prefill_email[type=text]").val()) {
        $("input.usermeta_prefill_email[type=text]").val(cookie_value);
    }
};

// Submits the form that contains the specified link. Handles ajax and
// traditional submits
fl.Form.submit_link = function(linkElement) {
    fl.Form.submit_form($(linkElement).closest("form"));
};
fl.Form.submit_form = function(form) {
    form = $(form);
    if (form[0] && form[0].onsubmit) {
        // this triggers if the html has an onsubmit="", eg form comes from rails' form_remote_tag().
        form[0].onsubmit();
    } else {
        // this triggers if the onsubmit handlers are set in jquery.
        form.submit();
    }
};
// Now that we're using links for submit buttons, we need to manually trap the enter key
// to submit forms that do not otherwise have submit buttons
// Key code 40 is the down arrow. 38 is the up arrow. If the previous
// key code is one of these, do not submit the form - the user is
// selecting from a list (e.g. an autocompleted list)
fl.Form.lastKeyCode = null;
fl.Form.initOnKeyPress = function() {
    log.setup("startup", "form")("Initializing Form KeyPress Handlers");

    $("form:not(:has(:submit)) :input:not(textarea,select,:hidden)").keypress(function(event){
        if (13 == event.keyCode && 38 != fl.Form.lastKeyCode && 40 != fl.Form.lastKeyCode){
            log.setup("interaction", "form")("Detected Enter key without immediately prior up or down key, submitting form");
            fl.Form.submit_form($(this).closest("form"));
        }
        fl.Form.lastKeyCode = event.keyCode;
    });
};
// Allows you to set defaults in text fields for any form elements on the page
// text_field_tag this_field, nil, { :preview_text => 'friend@email.com' }
fl.Form.initPreviewText = function() {
    $(":input[preview_text]").coolinput({ source: 'preview_text', blurClass: 'form_preview_text' });
};

// Creates a simple, lightweight tooltip that displays immediately
// below the text the mouse is pointing to. Unobtrusive:
// <dl class="static_tooltip">
//  <dt>Text 2</dt>
//  <dd>Tip 2</dd>
// </dl>
fl.ToolTip = {};
fl.ToolTip.init = function() {
    log.setup("startup", "tooltip")("Initializing Tooltips");

    $("dl.static_tooltip").each(function() {
        if ($(this).data('qtip')) return; // Skip lists which already have an initialized qtip object

        var el = $(this);
        var corner = { target: 'leftMiddle', tooltip: 'rightTop' };
        var tipCorner = "rightTop";
        if (el.closest("#sql_trace").length) {
            corner = { target: 'rightMiddle', tooltip: 'leftTop' };
            tipCorner = "leftTop";
        }
        var style = {
            name: "red",
            color: 'black',
            border: { width: 1 },
            fontSize: '11px',
            lineHeight: '130%',
            tip: {
                corner: tipCorner,
                size: { x: 12, y: 12 }
            }
        };
        if (!el.parent(".field_info")) {
            style.width = { max: 800 };
        }
        el.qtip({
            content: el.find("dd").html(),
            position: {
                target: el.find("dt"),
                corner: corner
            },
            show: {
                effect: {
                    type: 'slide',
                    length: 400
                }
            },
            hide: {
                fixed: true,
                effect: {
                    type: 'slide',
                    length: 200
                }
            },
            style: style
        });
    });
    log("Tooltip Initialization Complete");
};

fl.Validate = {}; // (mostly) DEPRECATED, replaced by validation plugin

// Returns true if the specified string is an integer
fl.Validate.IsInteger = function (str) { // Used by Credit Card Formatter -- Do not delete (yet)
    var i = -1;
    var max = str.length;
    while (++i < max) {
        var c = str.charCodeAt(i);
        if (57 < c || 48 > c){
            return false;
        }
    }
    return true;
};
fl.Validate.AutoInit = function() {
    log.setup("startup", "fl", "validate")("Initializing Form Validation");

    $("form").each(function() {
        $(this).validate({
            //debug: true, // enable to disable form submission, + some debug statements in validate plugin
            errorPlacement: function(error, element) { // TODO: test this placement thoroughly
                //error.css({ display: 'inline', 'float': 'none', margin: 0, width: 'auto' }); // reset some styles.  label.error styles isn't working, it's being applied before some other styles, and being overwritten
                var insertion_point = element.endOfLine(); // place error message after end of current line.
                insertion_point.after(error);
                if (error.offset().top < element.offset().top + element.height()) { // if the line had some space at the end, the error might not go onto a new line.
                    insertion_point.after("<br/>");
                }
            }
        });
    });
};
// In RJS: page << "fl.Validate.addFormError('addform', '#{error_messages_for(:brand)}');"
// Automatically adds a div tag to contain the error messages for this form if needed.
fl.Validate.addFormError = function(divId, errorMessages) {
    var el = $("#" + divId);
    var errorId = divId + "-E";
    var items = $('#' + errorId);
    var fullMessage = '<div id="' + errorId + '">' + errorMessages + '</div>';
    if (!items.length) {
        el.prepend(fullMessage);
    } else {
        items.html(fullMessage);
    }
};

fl.Validate.hideAllErrors = function() {
    $('.errorExplanation, label.error').hide();
};

fl.Refresh = {};
fl.Refresh.count = null;
fl.Refresh.set_message = function(statusId, message) {
    var el = $("#" + statusId);
    if (el.html() != message) {
        el.html(message);
    }
};
fl.Refresh.auto_refresh = function(statusId, interval, url) {
    fl.Refresh.countdown(statusId, interval, function() { // TODO: not the best way to do this
        window.location = url;
    });
};

// Used to update a div automatically with a countdown timer (e.g. 10
// seconds, 9 seconds, etc.). Callback, if provided, is invoked when 0
// is reached.
fl.Refresh.countdown = function(statusId, interval, callback) {
    if (!fl.Refresh.count) {
        fl.Refresh.count = {};
    }
    var count = (fl.Refresh.count[statusId] || 0) + 1;
    fl.Refresh.count[statusId] = count;

    var elapsed = (count / 4);
    var number_seconds = interval - elapsed;

    var minutes = parseInt(number_seconds / 60);
    var seconds = parseInt(number_seconds % 60).toString();
    if (1 == seconds.length){
        seconds = "0" + seconds;
    }

    fl.Refresh.set_message(statusId, minutes + ":" + seconds + "" + Locale.minutes);
    if (elapsed >= interval) {
        fl.Refresh.count[statusId] = null;
        if (callback) {
            callback();
        }
        return;
    }
    setTimeout(function() {
        fl.Refresh.countdown(statusId, interval, callback);
    }, 250);
};

fl.Omniture = {
    enabled: true,
    abTestGroup: '',
    channel: '',
    pageName: '',
    attributes: {},
    initialize: function(c,pn) {
        log.setup("startup", "fl", "omniture")("Initializing Omniture");
        fl.Omniture.channel = c;
        fl.Omniture.pageName = pn;
        fl.Omniture.attributes = {};
        fl.Omniture.trackingServer = "stat.gilt.com";
        fl.Omniture.trackingServerSecure = "sstat.gilt.com";
       //fl.Omniture.trackingServer = "stat." + gg.Site.currentSubsite.domain;
       //fl.Omniture.trackingServerSecure = "sstat." + gg.Site.currentSubsite.domain;
    },
    disable: function() {
        fl.Omniture.enabled = false;
    },
    addAttribute: function(k,v) {
        log.setup("fl", "omniture")("Adding attribute %s = %o to Omniture", k, v);
        if (!fl.Omniture.attributes[k]) {
            fl.Omniture.attributes[k] = [];
        }
        fl.Omniture.attributes[k][fl.Omniture.attributes[k].length] = v;
    },
    doTracking: function() {
        if (fl.Omniture.enabled) {
            log.setup("startup", "fl", "omniture")("Doing Tracking");
            var omniture_data = {
                channel: fl.Omniture.channel,
                pageName: fl.Omniture.pageName
            };
            if (fl.Omniture.abTestGroup) {
                log("AB Test Group");
                omniture_data.eVar11 = fl.Omniture.abTestGroup;
                omniture_data.prop5 = fl.Omniture.abTestGroup;
            }
            log("Joining attributes");
            var attrs = fl.Omniture.attributes;
            for (var k in attrs) {
                if (attrs.hasOwnProperty(k)) {
                    omniture_data[k] = fl.Omniture.attributes[k].join(',');
                }
            }
            log("Tracking...");
            $(function(){try{ 
                // Note: Passing tracking servers in the omniture_data doesn't seem to work.
                tmp = s.trackingServer;
                stmp = s.trackingServerSecure;
                s.trackingServer = fl.Omniture.trackingServer;
                s.trackingServerSecure = fl.Omniture.trackingServerSecure;
                s.t(omniture_data);
                s.trackingServer = tmp;
                s.trackingServerSecure = stmp;
                }catch(_){}});
        }
    },
    track: function(c,pn,attr) {
        log.setup("fl", "omniture")("Omniture Tracking");
        fl.Omniture.initialize(c, pn);
        for (var k in attr) {
            if (attr.hasOwnProperty(k)) {
                fl.Omniture.attributes[k] = attr[k];
            }
        }
        fl.Omniture.doTracking();
    }
};


// Set of functions to use a cookie as a key-value hash, with LRU space management to keep size under 4kb.
// Might get slow with lots of entries, but with 4kb ceiling, don't expect lots of entries.
fl.LruCookie = {
    persist: {},
    maxSize: {},
    // Internal low-level cookie read, does deserialization
    readCookie: function(cookie) {
        var rslt_string = fl.Util.readCookie(cookie);
        if (!rslt_string) {
            return [];
        }
        return (gg.parse_json(rslt_string) || []);
    },
    // Internal low-level cookie write, does serialization and space management
    writeCookie: function(cookie,state) {
        var state_string = JSON.stringify(state);
        var max = fl.LruCookie.maxSize[cookie] || 256;
        while (state_string.length > max && state.length) {
            state.pop();
            state_string = JSON.stringify(state);
        }
        if (state.length) {
            if (fl.LruCookie.persist[cookie]) {
                fl.Util.setPersistentCookie(cookie, state_string);
            } else {
                fl.Util.setSessionCookie(cookie, state_string);
            }
        } else {
            fl.Util.expireCookie(cookie);
        }
    },
    setPersist: function(cookie,persist) {
        fl.LruCookie.persist[cookie] = persist;
    },
    setMaxSize: function(cookie,maxSize) {
        fl.LruCookie.maxSize[cookie] = maxSize;
    },
    store: function(cookie, key, state) {
        /*var old_state = fl.LruCookie.readCookie(cookie), new_state = [];
        if (state) {
            new_state.push({ k: key, v: state });
        }
        var i = -1, max = old_state.length;
        while (++i < max) {
            var entry = old_state[i];
            if (entry && entry.k != key) {
                new_state.push(entry);
            }
        }
        fl.LruCookie.writeCookie(cookie, new_state);*/
        //if (state) { // are we storing anything
        var data = fl.LruCookie.readCookie(cookie); // load cookie
        if (data) { // does cookie exist
            //var i = -1, max = data.length;
            //while (++i < max) { // look from front
            var i = data.length;
            while (i--) { // look from back
                if (data[i].k == key) { // look for data with same key
                    data.splice(i, 1);  // if found, remove it
                    break;
                }
            }
            if (state) {
                data.unshift({ k: key, v: state }); // put new data on top of stack
            }
        } else if (state) {
            data = [{ k: key, v: state }]; // create cookie
        }
        fl.LruCookie.writeCookie(cookie, data); // write cookie
        //}
    },
    fetch: function(cookie, key) {
        var all_state = fl.LruCookie.readCookie(cookie);
        if (!all_state) {
            return null;
        }
        var i = -1;
        var max = all_state.length;
        while (++i < max) {
            var state = all_state[i];
            if (key == state.k) {
                // Move found state record to front of state array to maintain LRU order
                all_state.splice(i, 1);
                all_state.unshift(state);
                fl.LruCookie.writeCookie(cookie, all_state);
                return state.v;
            }
        }
        return null;
    }
};
var fl;
if (!fl) {
  fl = {};
}
if (!fl.Util) {
  fl.Util = {};
}
fl.Util.secondsToMinutes = function(seconds) {
    return '' + Math.round(seconds / 60);
};
fl.Util.secondsToMinutesSeconds = function(seconds) {
    var ss = seconds % 60;
    return '' + Math.floor(seconds / 60) + ':' + (ss < 10 ? ('0' + ss) : ss);
};

fl.Util.PreloadImage = function() {
    var i = arguments.length;
    while (i--) {
        (new Image()).src = fl.Init.ImageUri(arguments[i]);
    }
};
fl.Util.UniqueIndex = 0;
fl.Util.GetUniqueIndex = function() {
    return fl.Util.UniqueIndex++;
};
fl.Util.MaybeAssignID = function(el) {
/*    if ("function" != typeof el.attr) { // Temporary
        el = $(el);
    }*/
    if (!el.id()) {
        el.id('_fl_' + fl.Util.UniqueIndex++);
    }
};
fl.Util.IsEmpty = function(str) {
    return !str;
};
fl.Util.Alerted = false;
fl.Util.AlertOnce = function() {
    if (!fl.Util.Alerted) {
        fl.Util.Alerted = true;
    }
};
fl.Util.InitializedCache = {};
// Used to prevent double initialization. Note that this will set the
// element's ID if not already provided
fl.Util.isInitialized = function(prefix, el) {
    //if ("function" != typeof el.attr) { // Temporary
    //    el = $(el);
    //}
    fl.Util.MaybeAssignID(el);
    var key = prefix + el.id();
    if (!fl.Util.InitializedCache[key]) {
        fl.Util.InitializedCache[key] = true;
        return false;
    }
    return true;
};
fl.Util.setSessionCookie = function(name, value) {
    log.setup("cookie","util")("Setting Session Cookie %s=%o", name, value);
    document.cookie = name + "=" + encodeURIComponent(value) + ";path=/";
};
// expires: Number of seconds to keep this cookie. Defaults to 1 year
fl.Util.setPersistentCookie = function(name, value, expires) {
    log.setup("cookie","util")("Setting Persistent Cookie %s=%o", name, value);
    var d = new Date();
    if (expires) {
      d.setTime(d.getTime() + expires*1000);
    } else {
      d.setTime(d.getTime() + 31536000000); //365*24*60*60*1000
    }
    document.cookie = name + "=" + encodeURIComponent(value) + ";expires=" + d.toGMTString() + ";path=/";
};
fl.Util.expireCookie = function(name) {
    log.setup("cookie","util")("Expiring Cookie %s", name);
    var d = new Date();
    d.setTime(d.getTime() - 31536000000); //365*24*60*60*1000
    document.cookie = name + "=;expires=" + d.toGMTString() + ";path=/";
};
// Achtung!
// Do not use this for checksummed (hashed) cookies -- use readHashedCookie().
fl.Util.readCookie = function(name, opts) {
    log.setup("fl", "util")("Reading Cookie %s",name);

    // Prime the pump -- it is unsafe to retreive *_entire cookies without having first
    // called readHashedCookie on the pre-entire name. That call sets up the proper
    // cached regexes.
    if (m = name.match(/(\w+)_entire$/)) {
      fl.Util.readHashedCookie(m[1]);
    }

    // Not sure if this is actually any faster. If the regex is cached, it's about 10x faster.  We'll see
    var rcc = fl.Util.readCookie.cache;
    if (!rcc[name]) { // see if it's cached.  If not, create it
        if ((opts || {}).from_hash) {
            rcc[name] = new RegExp(";?" + name + "=[^_;]*_([^;]*);?");
            rcc[name + "_entire"] = new RegExp(";?" + name + "=([^;]*);?");
        } else {
            rcc[name] = new RegExp(";?" + name + "=([^;]*);?");
        }
        log("error", "Found uncached cookie regex.  Ask a dev to add this: \"%s\" to fl.Util.readCookie.cache", name);
    }
    var p = document.cookie.match(rcc[name]);
    if (p) {
        log("Found cookie").stop();
        return decodeURIComponent(p[1]);
    }
    log("Did not find cookie").stop();
    return null;
};
fl.Util.readCookie.cache = (function(){ // create regex objects -- might be a little slower than writing them all out, but it's easier to maintain
    var cache = {};
    var norm = [ "ca", "ca_expiration", "cart", "cart_0", "cart_1", "cart_2", "cart_3", "cart_4", "cart_5", "cart_6", "cart_7", "cart_8", "cart_9",
                 "email", "flash", "gender", "pca", "product_filter", "usermeta", "notifications" ];
    var hashed = [];
    var i = norm.length;
    while (i--) {
        cache[norm[i]] = new RegExp(";?" + norm[i] + "=([^;]*);?");
    }
    i = hashed.length;
    while (i--) {
        cache[hashed[i]] = new RegExp(";?" + hashed[i] + "=[^_;]*_([^;]*);?");
        cache[hashed[i] + "_entire"] = new RegExp(";?" + hashed[i] + "=([^;]*);?");
    }
    return cache;
})();
fl.Util.readHashedCookie = function(name) {
  return fl.Util.readCookie(name, { from_hash: true });
};
fl.Util.writeHashedCookieValue = function(name,key,value,opts) {
  var cookie_data = gg.parse_json(fl.Util.readCookie(name));
  cookie_data[key] = value;
  if ((opts || {}).session === true) {
    fl.Util.setSessionCookie(name,gg.to_json(cookie_data));
  } else {
    fl.Util.setPersistentCookie(name,gg.to_json(cookie_data));
  }
};
fl.Util.readUserId = function() {
  return fl.Util.readHashedCookie('user_id');
};
// First call rewrites this function SetOpacity to the correct one
// based on browser capability.
fl.Util.SetOpacity = function(elOrId, opacity) { // Deprecated TODO: replace with jquery
    var el = $(elOrId);
    if (!el.length) {
      el = $("#" + elOrId);
    }
    el.css("opacity", (opacity / 100) - 0.001);
};
fl.Util.unescapeSlashes = function(s) {
    return(s.replace(fl.Util.unescapeSlashes.regex,'/'));
};
fl.Util.unescapeSlashes.regex = /_slash_/g;
fl.Util.escapeSlashes = function(s) {
    return(s.replace(fl.Util.escapeSlashes.regex,'_slash_'));
};
fl.Util.escapeSlashes.regex = /\//g;

fl.Util.getDialog = function(id, opts) {
  var dialog = $("#" + id);
  if (!dialog.length) {
    dialog = $("<div id='" + id + "'>" + (opts.html || Locale.please_wait_loading_spin) + "</div>");
    dialog.appendTo("body");
  }
  if (!dialog.hasClass("ui-dialog-content")) {
    var close = function() {
      dialog.dialog("close").show();
    };
    dialog.dialog($.extend({
      title: "",
      autoOpen: false,
      modal: true,
      draggable: false,
      height: "auto",
      width: "auto",
      position: ["center", $("div.a_wrapper").offset().top],
      //position: "center",
      show: "custom", // fake "effect" so it doesn't just vanish.  handling it manually below.
      hide: "custom",
      closeOnEscape: (false !== opts.clickOverlay),
      open: function() {
        if ($.browser.msie && parseInt($.browser.version) == 6) {
          $("select").filter(function() { return !$(this).closest(".ui-dialog").length; }).hide();
        }
        var ov = dialog.data("dialog").overlay.$el;
        if (false !== opts.clickOverlay) {
          ov.click(close);
        }

        dialog.closest(".ui-dialog")
          .iff("undefined" == typeof opts.show)
            .show("slide", { direction: "up" })
          .others()
            .show();

        ov.css("opacity", 0)
          .fadeTo("fast", opts.overlayOpacity || 0.65);
      },
      beforeclose: function() {
        // close in two passes, have to do this because the overlay is destroyed too quickly otherwise.
        var ov = (dialog.data("dialog") && dialog.data("dialog").overlay.$el);
        if (ov && ov.filter(":visible").length) {
          ov.unbind("click", close)
            .show().fadeOut("fast", function() {
              dialog.dialog("close");
              if (!$(".ui-widget-overlay:visible").length) {
                $("select").show();
                ov.unwrap('.ui-effects-wrapper'); //what about dialog?
              }
            }
          );

          if (opts.hide == undefined) {
            dialog.closest(".ui-dialog")
              .hide("slide", { direction: "up" }, function() {
                $(this).unwrap('.ui-effects-wrapper');
                if (dialog.data("afterClose")) {
                  dialog.data("afterClose")(dialog);
                }
              }
            );
          } else {
            dialog.closest(".ui-dialog").hide();
            if (dialog.data("afterClose")) {
              dialog.data("afterClose")(dialog);
            }
          }
          return false;
        }
      }
    }, opts)).show().prev().find(".ui-dialog-titlebar-close span").text("");
    if (opts.additionalInit) {
      dialog.show()
      opts.additionalInit(dialog);
    }
  } else {
    dialog.dialog("option", opts);
    if (opts.html) {
      dialog.html(opts.html);
      if (opts.additionalInit) {
        opts.additionalInit(dialog);
      }
    }
  }
  if (opts.afterClose) {
    dialog.data("afterClose", opts.afterClose);
  }
  return dialog;
};
fl.Util.persistentCookiesEnabled = function() {
	fl.Util.setPersistentCookie('persistentCheck', 'true');
    var enabled = fl.Util.readCookie('persistentCheck') === 'true';
    fl.Util.expireCookie('persistentCheck');
    return enabled;
};
(function() {
  var d = function(a,b,c,d,e) {
    return;
    if (window.console) {
      console.debug("WINDOW: ",a,b,c,d,e);
    }
  };
  var xs_cookies = null;
  var read_queue = [];
  var msg_queue = [];
  var watches = {};

  var ie_max_message_length = 2048 - (gg_util_persistence_iframe_uri.length + (new Date()).getTime().toString().length + 4);
  var batch_message_max_length = ie_max_message_length - encodeURIComponent(JSON.stringify({ action: "batch", data: ""})).length;
  var hashMode = false;
  var batchBuffer = "";
  var sendPending = false;
  var handleMessage = function(message) {
    message = JSON.parse(decodeURIComponent(message.data));
    sendPending = false;
    d("Handling Message", message);
    if ("batch" == message.action || "batchEnd" == message.action) {
      d("Appending Batch Message", message.data);
      batchBuffer += message.data;
      if ("batchEnd" == message.action) {
        d("Flushing Batch");
        handleMessage(batchBuffer);
        batchBuffer = "";
      }
    } else if ("next" == message.action) {
      d("Sending Next Message");
      messageQueueWorker();
    } else if ("cookies" == message.action) {
      d("Receiving Cookies", message.data);
      xs_cookies = {};
      $(message.data.split(";"))
        .each(function() {
          xs_cookies[this.split("=")[0].replace(/^\s/,'')] = decodeURIComponent(this.split("=").length > 1 ? this.split("=")[1] : "");
        });
      d("Doing callbacks for queued cookie reads");
      $(read_queue).each(function() {
        this.callback(xs_cookies[this.name]);
      });
    } else if ("cookie" == message.action) {
      d("Cookie Received", message.data.name, message.data.value);
      if (!xs_cookies) {
        xs_cookies = {};
      }
      xs_cookies[message.data.name] = message.data.value;
      $(read_queue).filter(function() {
        if (message.data.name == this.name) {
          this.callback(xs_cookies[this.name]);
          return false;
        }
        return true;
      });
    } else if ("cookiechanged" == message.action) {
      d("Cookie Changed", message.data.name);
      if (xs_cookies) {
        xs_cookies[message.data.name] = message.data.value;
      }
      d("Doing callbacks for watched cookie");
      if (watches[message.data.name]) {
        $(watches[message.data.name]).each(function() {
          this(message.data.value);
        });
      }
    } else if ("ready" == message.action) {
      d("Iframe is ready");
      if (!hashMode) {
        d("Asking for cookies");
        postMessage({ action: "getcookies" });
        var run_queue = msg_queue;
        msg_queue = null;
        $(run_queue).each(function() {
          postMessage(this);
        });
      } else {
        d("Adding requests for each requested cookie");
        $(read_queue).each(function() {
          postMessage({ action: "getcookie", data: this.name });
        });
      }
    }
    if (hashMode) {
      d("Asking for next message");
      if (!msg_queue.length) {
        postMessage({ action: "next" });
      }
    }
  };
  var messageQueueWorker = function() {
    if (msg_queue.length && !sendPending) {
      sendPending = true;
      d("Sending Queued Message");
      $.postMessage(encodeURIComponent(JSON.stringify(msg_queue.pop())), gg_util_persistence_iframe_uri, window.persistence_iframe);
    }
  };
  $(function() {
    if ($.receiveMessage) {
      $.receiveMessage(function(message) {
        d("Message Received", message.data);
        if (!message.source) {
          d("We're in Hash Mode");
          hashMode = true;
          document.location.hash = "#";
        } else if (message.source != window.persistence_iframe) {
          d("Invalid Source, Stopping");
          return;
        }
        handleMessage(message);
      });
    }
  });
  var postMessage = function(msg) {
    d("postMessage", JSON.stringify(msg));
    if (hashMode) {
      d("postMessage::hashMode");
      var message = encodeURIComponent(JSON.stringify(msg));
      if (message.length > ie_max_message_length) {
        d("Batching Message");
        while (message.length) {
          var action = "batch";
          var l = batch_message_max_length;
          var data = msg.slice(0, l);
          while (encodeURIComponent(data).length > batch_message_max_length) {
            l -= Math.min(1, (encodeURIComponent(data).length - batch_message_max_length) / 3);
            data = data.slice(0, l);
          }
          if (data.length == msg.length) {
            action = "batchEnd";
          }
          msg = msg.slice(l);
          d("Adding Batch Message to Queue");
          msg_queue.push({ action: action, data: data });
        }
      } else {
        d("Adding Message to Queue");
        msg_queue.push(msg);
      }
      messageQueueWorker();
    } else {
      d("postMessage::normalMode");
      if (msg_queue) {
        d("Queueing Message");
        msg_queue.push(msg);
      } else {
        d("Sending Message");
        $.postMessage(encodeURIComponent(JSON.stringify(msg)), gg_util_persistence_iframe_uri, window.persistence_iframe);
      }
    }
  };
  fl.Util.readXSCookie = function(name, callback, user_specific) {
    callback(fl.Util.readCookie(name));
    return;

    if (user_specific !== false) {
      name = (fl.Util.readHashedCookie("user_id") || "all") + "_" + name;
    }

    d("ReadXSCookie", name);
    if (xs_cookies && xs_cookies.hasOwnProperty(name)) {
      callback(xs_cookies[name]);
    } else {
      read_queue.push({ name: name, callback: callback });
      if (hashMode) {
        postMessage({ action: "getcookie", data: name });
      }
    }
  };
  fl.Util.setXSCookie = function(name, value, cookie_opts, user_specific) {
    fl.Util.setPersistentCookie(name, value);
    return;

    if (user_specific !== false) {
      name = (fl.Util.readHashedCookie("user_id") || "all") + "_" + name;
    }
    d("SetXSCookie", name, value);
    postMessage({ action: "setcookie", data: name + "=" + value + ";" + cookie_opts + ";path=/"});
    if (xs_cookies) {
      xs_cookies[name] = value;
    }
  };
  fl.Util.watchCookie = function(name, callback, user_specific) {
    callback();
    return;

    if (user_specific !== false) {
      name = (fl.Util.readHashedCookie("user_id") || "all") + "_" + name;
    }
    d("WatchCookie", name);
    if (!watches[name]) {
      watches[name] = [];
      postMessage({ action: "watch", data: name });
    }
    watches[name].push(callback);
  };
})();
String.prototype.rsplit=function(F){var E=this;var A=F.exec(E);var G=new Array();while(A!=null){var D=A.index;var C=F.lastIndex;if((D)!=0){var B=E.substring(0,D);G.push(E.substring(0,D));E=E.slice(D)}G.push(A[0]);E=E.slice(A[0].length);A=F.exec(E)}if(!E==""){G.push(E)}return G};String.prototype.chop=function(){return this.substr(0,this.length-1)};var EjsScanner=function(B,C,A){this.left_delimiter=C+"%";this.right_delimiter="%"+A;this.double_left=C+"%%";this.double_right="%%"+A;this.left_equal=C+"%=";this.left_comment=C+"%#";if(C=="["){this.SplitRegexp=/(\[%%)|(%%\])|(\[%=)|(\[%#)|(\[%)|(%\]\n)|(%\])|(\n)/}else{this.SplitRegexp=new RegExp("("+this.double_left+")|(%%"+this.double_right+")|("+this.left_equal+")|("+this.left_comment+")|("+this.left_delimiter+")|("+this.right_delimiter+"\n)|("+this.right_delimiter+")|(\n)")}this.source=B;this.stag=null;this.lines=0};EjsView={};EjsScanner.to_text=function(A){if(A==null||A===undefined){return""}if(A instanceof Date){return A.toDateString()}if(A.toString){return A.toString()}return""};EjsScanner.prototype={scan:function(D){scanline=this.scanline;regex=this.SplitRegexp;if(!this.source==""){var C=this.source.rsplit(/\n/);for(var A=0;A<C.length;A++){var B=C[A];this.scanline(B,regex,D)}}},scanline:function(A,D,G){this.lines++;var E=A.rsplit(D);for(var C=0;C<E.length;C++){var B=E[C];if(B!=null){try{G(B,this)}catch(F){throw {type:"EjsScanner",line:this.lines}}}}}};var EjsBuffer=function(B,C){this.line=new Array();this.script="";this.pre_cmd=B;this.post_cmd=C;for(var A=0;A<this.pre_cmd.length;A++){this.push(B[A])}};EjsBuffer.prototype={push:function(A){this.line.push(A)},cr:function(){this.script=this.script+this.line.join("; ");this.line=new Array();this.script=this.script+"\n"},close:function(){if(this.line.length>0){for(var A=0;A<this.post_cmd.length;A++){this.push(pre_cmd[A])}this.script=this.script+this.line.join("; ");line=null}}};EjsCompiler=function(B,C){this.pre_cmd=['___ejsO = "";'];this.post_cmd=new Array();this.source=" ";if(B!=null){if(typeof B=="string"){B=B.replace(/\r\n/g,"\n");B=B.replace(/\r/g,"\n");this.source=B}else{if(B.innerHTML){this.source=B.innerHTML}}if(typeof this.source!="string"){this.source=""}}C=C||"<";var A=">";switch(C){case"[":A="]";break;case"<":break;default:throw C+" is not a supported deliminator";break}this.scanner=new EjsScanner(this.source,C,A);this.out=""};EjsCompiler.prototype={compile:function(options){options=options||{};this.out="";var put_cmd="___ejsO += ";var insert_cmd=put_cmd;var buff=new EjsBuffer(this.pre_cmd,this.post_cmd);var content="";var clean=function(content){content=content.replace(/\\/g,"\\\\");content=content.replace(/\n/g,"\\n");content=content.replace(/"/g,'\\"');return content};this.scanner.scan(function(token,scanner){if(scanner.stag==null){switch(token){case"\n":content=content+"\n";buff.push(put_cmd+'"'+clean(content)+'";');buff.cr();content="";break;case scanner.left_delimiter:case scanner.left_equal:case scanner.left_comment:scanner.stag=token;if(content.length>0){buff.push(put_cmd+'"'+clean(content)+'"')}content="";break;case scanner.double_left:content=content+scanner.left_delimiter;break;default:content=content+token;break}}else{switch(token){case scanner.right_delimiter:switch(scanner.stag){case scanner.left_delimiter:if(content[content.length-1]=="\n"){content=content.chop();buff.push(content);buff.cr()}else{buff.push(content)}break;case scanner.left_equal:buff.push(insert_cmd+"(EjsScanner.to_text("+content+"))");break}scanner.stag=null;content="";break;case scanner.double_right:content=content+scanner.right_delimiter;break;default:content=content+token;break}}});if(content.length>0){buff.push(put_cmd+'"'+clean(content)+'"')}buff.close();this.out=buff.script+";";var to_be_evaled="this.process = function(_CONTEXT) { try { with(EjsView) { with (_CONTEXT) {"+this.out+" return ___ejsO;}}}catch(e){e.lineNumber=null;throw e;}};";try{eval(to_be_evaled)}catch(e){if(typeof JSLINT!="undefined"){JSLINT(this.out);for(var i=0;i<JSLINT.errors.length;i++){var error=JSLINT.errors[i];if(error.reason!="Unnecessary semicolon."){error.line++;var e=new Error();e.lineNumber=error.line;e.message=error.reason;if(options.url){e.fileName=options.url}throw e}}}else{throw e}}}};EJS=function(B){this.set_options(B);if(B.url){var C=EJS.get(B.url,this.cache);if(C){return C}if(C==EJS.INVALID_PATH){return null}this.text=EJS.request(B.url);if(this.text==null){throw"There is no template at "+B.url}this.name=B.url}else{if(B.element){if(typeof B.element=="string"){var A=B.element;B.element=document.getElementById(B.element);if(B.element==null){throw A+"does not exist!"}}if(B.element.value){this.text=B.element.value}else{this.text=B.element.innerHTML}this.name=B.element.id;this.type="["}}var C=new EjsCompiler(this.text,this.type);C.compile(B);EJS.update(this.name,this);this.template=C};EJS.config=function(B){EJS.cache=B.cache!=null?B.cache:EJS.cache;EJS.type=B.type!=null?B.type:EJS.type;var A={};EJS.get=function(D,C){if(C==false){return null}if(A[D]){return A[D]}return null};EJS.update=function(D,C){if(D==null){return }A[D]=C};EJS.INVALID_PATH=-1};EJS.config({cache:true,type:"<"});EJS.prototype={render:function(A){return this.template.process.call(A,A)},out:function(){return this.template.out},set_options:function(A){this.type=A.type!=null?A.type:EJS.type;this.cache=A.cache!=null?A.cache:EJS.cache;this.text=A.text!=null?A.text:null;this.name=A.name!=null?A.name:null},update:function(element,options){if(typeof element=="string"){element=document.getElementById(element)}if(options==null){_template=this;return function(object){EJS.prototype.update.call(_template,element,object)}}if(typeof options=="string"){params={};params.url=options;_template=this;params.onComplete=function(request){var object=eval(request.responseText);EJS.prototype.update.call(_template,element,object)};EJS.ajax_request(params)}else{element.innerHTML=this.render(options)}}};EJS.newRequest=function(){var C=[function(){return new XMLHttpRequest()},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Microsoft.XMLHTTP")}];for(var A=0;A<C.length;A++){try{var B=C[A]();if(B!=null){return B}}catch(D){continue}}};EJS.request=function(C){var A=new EJS.newRequest();A.open("GET",C,false);try{A.send(null)}catch(B){return null}if(A.status==404||A.status==2||(A.status==0&&A.responseText=="")){return null}return A.responseText};EJS.ajax_request=function(B){B.method=(B.method?B.method:"GET");var A=new EJS.newRequest();A.onreadystatechange=function(){if(A.readyState==4){if(A.status==200){B.onComplete(A)}else{B.onComplete(A)}}};A.open(B.method,B.url);A.send(null)};EjsView=function(){};EjsView.date_tag=function(C,O,A){if(!(O instanceof Date)){O=new Date()}var B=["January","February","March","April","May","June","July","August","September","October","November","December"];var G=[],D=[],P=[];var J=O.getFullYear();var H=O.getMonth();var N=O.getDate();for(var M=J-15;M<J+15;M++){G.push({value:M,text:M})}for(var E=0;E<12;E++){D.push({value:(E),text:B[E]})}for(var I=0;I<31;I++){P.push({value:(I+1),text:(I+1)})}var L=this.select_tag(C+"[year]",J,G,{id:C+"[year]"});var F=this.select_tag(C+"[month]",H,D,{id:C+"[month]"});var K=this.select_tag(C+"[day]",N,P,{id:C+"[day]"});return L+F+K};EjsView.form_tag=function(B,A){A=A||{};A.action=B;if(A.multipart==true){A.method="post";A.enctype="multipart/form-data"}return this.start_tag_for("form",A)};EjsView.form_tag_end=function(){return this.tag_end("form")};EjsView.hidden_field_tag=function(A,C,B){return this.input_field_tag(A,C,"hidden",B)};EjsView.input_field_tag=function(A,D,C,B){B=B||{};B.id=B.id||A;B.value=D||"";B.type=C||"text";B.name=A;return this.single_tag_for("input",B)};EjsView.is_current_page=function(A){if(window.location.href==A||window.location.pathname==A){return true}return false};EjsView.link_to=function(B,A,C){if(!B){var B="null"}if(!C){var C={}}if(C.confirm){C.onclick=' var ret_confirm = confirm("'+C.confirm+'"); if(!ret_confirm){ return false;} ';C.confirm=null}C.href=A;return this.start_tag_for("a",C)+B+this.tag_end("a")};EjsView.submit_link_to=function(B,A,C){if(!B){var B="null"}if(!C){var C={}}C.onclick=C.onclick||"";if(C.confirm){C.onclick=' var ret_confirm = confirm("'+C.confirm+'"); if(!ret_confirm){ return false;} ';C.confirm=null}C.value=B;C.type="submit";C.onclick=C.onclick+(A?this.url_for(A):"")+"return false;";return this.start_tag_for("input",C)};EjsView.link_to_if=function(F,B,A,D,C,E){return this.link_to_unless((F==false),B,A,D,C,E)};EjsView.link_to_unless=function(E,B,A,C,D){C=C||{};if(E){if(D&&typeof D=="function"){return D(B,A,C,D)}else{return B}}else{return this.link_to(B,A,C)}};EjsView.link_to_unless_current=function(B,A,C,D){C=C||{};return this.link_to_unless(this.is_current_page(A),B,A,C,D)};EjsView.password_field_tag=function(A,C,B){return this.input_field_tag(A,C,"password",B)};EjsView.select_tag=function(D,G,H,F){F=F||{};F.id=F.id||D;F.value=G;F.name=D;var B="";B+=this.start_tag_for("select",F);for(var E=0;E<H.length;E++){var C=H[E];var A={value:C.value};if(C.value==G){A.selected="selected"}B+=this.start_tag_for("option",A)+C.text+this.tag_end("option")}B+=this.tag_end("select");return B};EjsView.single_tag_for=function(A,B){return this.tag(A,B,"/>")};EjsView.start_tag_for=function(A,B){return this.tag(A,B)};EjsView.submit_tag=function(A,B){B=B||{};B.type=B.type||"submit";B.value=A||"Submit";return this.single_tag_for("input",B)};EjsView.tag=function(C,E,D){if(!D){var D=">"}var B=" ";for(var A in E){if(E[A]!=null){var F=E[A].toString()}else{var F=""}if(A=="Class"){A="class"}if(F.indexOf("'")!=-1){B+=A+'="'+F+'" '}else{B+=A+"='"+F+"' "}}return"<"+C+B+D};EjsView.tag_end=function(A){return"</"+A+">"};EjsView.text_area_tag=function(A,C,B){B=B||{};B.id=B.id||A;B.name=B.name||A;C=C||"";if(B.size){B.cols=B.size.split("x")[0];B.rows=B.size.split("x")[1];delete B.size}B.cols=B.cols||50;B.rows=B.rows||4;return this.start_tag_for("textarea",B)+C+this.tag_end("textarea")};EjsView.text_tag=EjsView.text_area_tag;EjsView.text_field_tag=function(A,C,B){return this.input_field_tag(A,C,"text",B)};EjsView.url_for=function(A){return'window.location="'+A+'";'};EjsView.img_tag=function(B,C,A){A=A||{};A.src=B;A.alt=C;return EjsView.single_tag_for("img",A)}
var Gilt;
if (!Gilt) {
  Gilt = {};
}
Gilt.Notifications = {
  isOpen: false,
  doPopups: true,
  showSecondsAtNMinutes: 2,
  element: null,
  messages: [],
  expired: [],
  specialMessage: "",
  nextKey: 0,
  enabled: false,
  scrollWithPage: false,
  expectingCookieChange: false,
  initialRestore: true,
  countdownTimer: null,
  init: function() {
    Gilt.Notifications.enabled = true;
    Gilt.Notifications.element = $("#carousel-notifications-container");
    if ($.browser.msie && 7 > parseInt($.browser.version)) {
      DD_belatedPNG.fix("#carousel-notifications-bg, #carousel-notifications-bottom, #carousel-notifications-tab, span.notification-icon");
    }
    Gilt.Notifications.element.css({
      top: -Gilt.Notifications.element.height() - 1,
      left: $("#carousel-nav-notifications-placeholder").offset().left - $("#carousel-nav-top-bar").offset().left - $("#carousel-notifications-container").width() + $("#carousel-notifications-tab").width() - 16
    });
    Gilt.Notifications.element.find("#carousel-notifications-snooze").click(function(ev) {
      ev.preventDefault();
      Gilt.Notifications.snooze();
    });
    Gilt.Notifications.element.find("#carousel-notifications-hide").click(function(ev) {
      ev.preventDefault();
      Gilt.Notifications.hide();
    });
    Gilt.Notifications.element.find("span.notification-toggle").click(function() {
      if (Gilt.Notifications.isOpen) {
        Gilt.Notifications.snooze();
      } else {
        Gilt.Notifications.show();
      }
    });
    fl.Util.watchCookie("notifications", function() {
      if (!Gilt.Notifications.expectingCookieChange) {
        Gilt.Notifications.restore();
      }
      Gilt.Notifications.expectingCookieChange = false;
    });
    Gilt.Notifications.restore();
    Gilt.Notifications.countdown();
    if (Gilt.Notifications.scrollWithPage) {
      var scrollTimer;
      $(window).scroll(function() {
        clearTimeout(scrollTimer);
        if (Gilt.Notifications.element.find("#carousel-notifications-current div.carousel-notification-item").length && !$("div.ui-widget-overlay:visible").length) {
          if (Gilt.Notifications.element.filter(":visible").length) {
            if (!Gilt.Notifications.isOpen) {
              Gilt.Notifications.element.find("#carousel-notifications-bg").css({ visibility: "hidden" });
            }
            Gilt.Notifications.element.fadeOut();
          }
          scrollTimer = setTimeout(function() {
            Gilt.Notifications.element.find("#carousel-notifications-bg").css({ visibility: "visible" });
            Gilt.Notifications.element
              .css({ top: $("html").scrollTop() - (Gilt.Notifications.element.height() + 33) })
              .show()
              .animate({ top: $("html").scrollTop() - (Gilt.Notifications.isOpen ? 0 : Gilt.Notifications.element.height()) });
          }, 1000);
        }
      });
    }
  },
  add: function(message, restoring) {
    if (!Gilt.Notifications.enabled) {
      return;
    }
    if (!message.jquery) {
      if (Gilt.Notifications.templates.hasOwnProperty(message.k)) {
        var msg = message;
        if (!restoring) {
          msg.z = Gilt.Notifications.nextKey++;
          Gilt.Notifications.messages.push(msg);
          Gilt.Notifications.persist();
        }
        message = Gilt.Notifications.templates[msg.k].apply(null, msg.v);
        message.data("notification-item", msg);
      }
    }
    Gilt.Notifications.element.find("#carousel-notifications-new").prepend(message);
    //Gilt.Notifications.snooze(true);
    //if (Gilt.Notifications.isOpen) {
    //  message.hide().show("blind");
    //} else {
    //  Gilt.Notifications.element.css({ top: -Gilt.Notifications.element.height() - 1 });
    //}
    return message;
  },
  checkForAutoRemovals: function() {
    var current_time = (new Date()).getTime();
    var persistRequired = false;
    var removal = function(array) {
      for (var i = 0; i < array.length; ++i) {
        if (array[i].r && array[i].r <= current_time) {
          Gilt.Notifications.remove(Gilt.Notifications.element.find("div.carousel-notification-item:not(div.carousel-notification-permanent-item)").filter(function() {
            return $(this).data("notification-item").z == array[i].z;
          }), true);
          array.splice(i--, 1);
          persistRequired = true;
        }
      }
    };
    removal(Gilt.Notifications.messages);
    removal(Gilt.Notifications.expired);
    if (persistRequired) {
      Gilt.Notifications.persist();
    }
  },
  remove: function(el, uionly) {
    if (!Gilt.Notifications.enabled || !el.length) {
      return;
    }
    var item = el.data("notification-item");
    if (!uionly) {
      var removal = function(array) {
        for (var i = 0; i < array.length; ++i) {
          if (array[i].z == item.z) {
            array.splice(i, 1);
          }
        }
      };
      removal(Gilt.Notifications.messages);
      removal(Gilt.Notifications.expired);
      Gilt.Notifications.persist();
    }
    if (Gilt.Notifications.isOpen && el.filter(":visible")) {
      el.hide("blind", function() {
        el.remove();
        if (!Gilt.Notifications.element.find("div.carousel-notification-item:visible").length) {
          Gilt.Notifications.snooze();
          //if (!Gilt.Notifications.element.find("#carousel-notifications-none:visible").length) {
          //  Gilt.Notifications.element.find("#carousel-notifications-none").show("blind");
          //}
        }
      });
    } else {
      el.remove();
      Gilt.Notifications.snooze(true);
    }
    if (!Gilt.Notifications.element.find("#carousel-notifications-current div.carousel-notification-item").length) {
      Gilt.Notifications.element.find("#carousel-notifications-tab").addClass("notifications-none");
    }
  },
  expire: function(el, restoring) {
    if (!Gilt.Notifications.enabled) {
      return;
    }
    if (!$("#carousel-notifications-old:visible").length && $("#carousel-notifications-current:visible").length) {
      el.hide("blind", function() {
        Gilt.Notifications.element.find("#carousel-notifications-old").prepend(el);
        el.show();
        if (!Gilt.Notifications.element.find("#carousel-notifications-current div.carousel-notification-item").length) {
          Gilt.Notifications.snooze();
          if (Gilt.Notifications.element.hasClass("fixed")) {
            Gilt.Notifications.element.removeClass("fixed");
            var placeholder = $("#carousel-nav-notifications-placeholder");
            Gilt.Notifications.element.css({ left: placeholder.offset().left - $("#carousel-nav-top-bar").offset().left + placeholder.width() - Gilt.Notifications.element.width() + 16 });
          }
          if (!Gilt.Notifications.element.find("#carousel-notifications-current div.carousel-notification-item").length) {
            Gilt.Notifications.element.find("#carousel-notifications-tab").addClass("notifications-none");
          }
        }
      });
    } else {
      Gilt.Notifications.element.find("#carousel-notifications-old").prepend(el);
      if (Gilt.Notifications.isOpen) {
        el.hide().show("blind");
        if (Gilt.Notifications.element.find("#carousel-notifications-none:visible").length) {
          Gilt.Notifications.element.find("#carousel-notifications-none").hide("blind");
        }
      } else {
        Gilt.Notifications.snooze(true);
      }
    }
    if (!restoring) {
      Gilt.Notifications.alreadyNotifiedOfExpiringMessage = false;
      if (!Gilt.Notifications.element.find("#carousel-notifications-current div.carousel-notification-item").length) {
        Gilt.Notifications.element.find("#carousel-notifications-tab").addClass("notifications-none");
      }
      var item = el.data("notification-item");
      for (var i = 0; i < Gilt.Notifications.messages.length; ++i) {
        if (Gilt.Notifications.messages[i].z == item.z) {
          Gilt.Notifications.expired.push(Gilt.Notifications.messages.splice(i, 1)[0]);
        }
      }
      Gilt.Notifications.persist();
    }
  },
  message: function(message, restoring) {
    if (!Gilt.Notifications.enabled) {
      return;
    }
    Gilt.Notifications.specialMessage = message;
    Gilt.Notifications.element
      .find("div.carousel-notification-message")
        .text(message)
        .iff(Gilt.Notifications.isOpen)
          [message.length ? "show" : "hide"]("blind")
        .others()
          .toggle(!!message.length);
    if (!restoring) {
      Gilt.Notifications.persist();
    }
  },
  persist: function() {
    Gilt.Notifications.checkForAutoRemovals();
    Gilt.Notifications.expectingCookieChange = true;
    var d = new Date();
    d.setTime(d.getTime() + 31536000000);
    fl.Util.setXSCookie("notifications", JSON.stringify({ m:Gilt.Notifications.messages, e:Gilt.Notifications.expired, p:Gilt.Notifications.doPopups, s:Gilt.Notifications.specialMessage }), "expires=" + d.toGMTString());
  },
  restore: function() {
    fl.Util.readXSCookie("notifications", function(notifications_cookie) {
      var data = $.extend({ m:[], e:[], p:Gilt.Notifications.doPopups, s:"" }, gg.parse_json(notifications_cookie));
      Gilt.Notifications.element.find("#carousel-notifications-new, #carousel-notifications-old").find("div").remove();
      Gilt.Notifications.messages = data.m;
      Gilt.Notifications.expired = data.e;
      Gilt.Notifications.checkForAutoRemovals();
      for (var i = 0; i < data.m.length; ++i) {
        Gilt.Notifications.add(data.m[i], true);
        if (data.m[i].z >= Gilt.Notifications.nextKey) {
          Gilt.Notifications.nextKey = data.m[i].z + 1;
        }
      }
      for (i = 0; i < data.e.length; ++i) {
        Gilt.Notifications.expire(Gilt.Notifications.add(data.e[i], true), true);
        if (data.e[i].z >= Gilt.Notifications.nextKey) {
          Gilt.Notifications.nextKey = data.e[i].z + 1;
        }
      }
      Gilt.Notifications.doPopups = data.p;
      Gilt.Notifications.message(data.s, true);
      if (Gilt.Notifications.initialRestore && Gilt.Notifications.doPopups && Gilt.Notifications.anythingExpiringSoon()) {
        //Gilt.Notifications.popdown(true);
      }
      else if (Gilt.Notifications.isOpen) {
        if ($("#carousel-notifications-old:visible").length) {
          Gilt.Notifications.show();
        } else {
          Gilt.Notifications.popdown();
        }
      } else {
        Gilt.Notifications.snooze(true);
      }
      Gilt.Notifications.initialRestore = false;
    });
  },
  snooze: function(fromTop) {
    if (!Gilt.Notifications.enabled) {
      return;
    }
    var itemsLeft = Gilt.Notifications.element.find("div.carousel-notification-item:visible").length;
    if (fromTop) {
      Gilt.Notifications.element.css({ top: ( itemsLeft && Gilt.Notifications.scrollWithPage ? $("html").scrollTop() : 0) - Gilt.Notifications.element.height() - 1 });
      Gilt.Notifications.isOpen = false;
    } else {
      Gilt.Notifications.element.animate({ top: ( itemsLeft && Gilt.Notifications.scrollWithPage ? $("html").scrollTop() : 0) - Gilt.Notifications.element.height() - 1 }, function() {
        Gilt.Notifications.element.find("#carousel-notifications-none").hide();
        Gilt.Notifications.element.css({ top: ( itemsLeft && Gilt.Notifications.scrollWithPage ? $("html").scrollTop() : 0) - Gilt.Notifications.element.height() - 1 });
        Gilt.Notifications.isOpen = false;
      });
    }
  },
  hide: function() {
    if (!Gilt.Notifications.enabled) {
      return;
    }
    Gilt.Notifications.snooze();
    Gilt.Notifications.doPopups = false;
    Gilt.Notifications.persist();
  },
  show: function(fromTop) {
    if (!Gilt.Notifications.enabled || $(".ui-dialog:visible").length) {
      return;
    }
    if (fromTop) {
      Gilt.Notifications.snooze(fromTop);
    }
    Gilt.Notifications.checkForAutoRemovals();
    if (!Gilt.Notifications.element.find("#carousel-notifications-current, #carousel-notifications-old").find("div.carousel-notification-item").length) {
      Gilt.Notifications.element.find("#carousel-notifications-none").show();
    }
    //if (Gilt.Notifications.element.find("#carousel-notifications-current, #carousel-notifications-old").find("div.carousel-notification-item").length) {
      if (Gilt.Notifications.isOpen) {
        Gilt.Notifications.element
          .find("#carousel-notifications-old")
            .not(":visible")
              .show("blind");
      } else {
        Gilt.Notifications.element.find("#carousel-notifications-old").show();
        Gilt.Notifications.isOpen = true;
        Gilt.Notifications.element.animate({ top: (Gilt.Notifications.scrollWithPage ? $("html").scrollTop() : 0) });
        Gilt.Notifications.countdown();
      }
    //}
    if (!Gilt.Notifications.doPopups) {
      Gilt.Notifications.doPopups = true;
      Gilt.Notifications.persist();
    }
  },
  popdown: function(fromTop) {
    if (!Gilt.Notifications.enabled || $(".ui-dialog:visible").length) {
      return;
    }
    if (fromTop) {
      Gilt.Notifications.snooze(fromTop);
    }
    Gilt.Notifications.checkForAutoRemovals();
    if (Gilt.Notifications.doPopups && Gilt.Notifications.element.find("#carousel-notifications-current div.carousel-notification-item").length) {
      if (Gilt.Notifications.isOpen) {
        Gilt.Notifications.element
          .find("#carousel-notifications-old")
            .filter(":visible")
              .hide("blind");
      } else {
        Gilt.Notifications.element.find("#carousel-notifications-old").hide();
        Gilt.Notifications.isOpen = true;
        Gilt.Notifications.element.animate({ top: (Gilt.Notifications.scrollWithPage ? $("html").scrollTop() : 0) });
        Gilt.Notifications.countdown();
      }
    }
  },
  countdown: function() {
    clearTimeout(Gilt.Notifications.countdownTimer);
    var current_time = (new Date()).getTime();
    Gilt.Notifications.element.find("#carousel-notifications-new div.carousel-notification-item[data-countdownto]").each(function() {
      var el = $(this);
      if (((parseInt(el.attr("data-countdownto")) - current_time) / 60000) < Gilt.Notifications.showSecondsAtNMinutes) {
        el.prependTo(Gilt.Notifications.element.find("#carousel-notifications-current"));
        if (Gilt.Notifications.isOpen) {
          if (Gilt.Notifications.element.find("#carousel-notifications-none:visible").length) {
            Gilt.Notifications.element.find("#carousel-notifications-none").hide("blind");
          }
          el.hide().show("blind");
        } else {
          Gilt.Notifications.snooze(true);
        }
        Gilt.Notifications.element.find("#carousel-notifications-tab.notifications-none").removeClass("notifications-none");
      }
    });
    if (Gilt.Notifications.anythingExpiringSoon()) {
      if (!Gilt.Notifications.element.hasClass("fixed")) {
        Gilt.Notifications.element.addClass("fixed");
        var placeholder = $("#carousel-nav-notifications-placeholder");
        Gilt.Notifications.element.css({ left: placeholder.offset().left + placeholder.width() - Gilt.Notifications.element.width() + 16 });
      }
    } else {
      if (Gilt.Notifications.element.hasClass("fixed")) {
        Gilt.Notifications.element.removeClass("fixed");
        placeholder = $("#carousel-nav-notifications-placeholder");
        Gilt.Notifications.element.css({ left: placeholder.offset().left - $("#carousel-nav-top-bar").offset().left + placeholder.width() - Gilt.Notifications.element.width() + 16 });
      }
    }
    if (Gilt.Notifications.isOpen) {
      Gilt.Notifications.checkForAutoRemovals();
      var pollOnSecond = false;
      Gilt.Notifications.element.find("div.carousel-notification-item[data-countdownto]:visible").each(function() {
        var el = $(this);
        var remainingTime = parseInt(el.attr("data-countdownto")) - current_time;
        if (remainingTime > 0) {
          var minutes = remainingTime / 60000;
          //if (minutes < Gilt.Notifications.showSecondsAtNMinutes) {
            pollOnSecond = true;
            var seconds = (remainingTime % 60000) / 1000;
            var time_string = Math.floor(minutes) + ":" + (seconds < 10 ? "0" : "") + Math.floor(seconds);
            el.find("span").text(el.attr("data-countdownmessage").replace("@@time@@", time_string + " minutes"));
          //} else {
          //  el.find("span").text(el.attr("data-countdownmessage").replace("@@time@@", Math.round(minutes) + " more minutes"));
          //}
        } else {
          el.removeAttr("data-countdownto")
            .find("span")
              .text(el.attr("data-countdowncomplete"));
          Gilt.Notifications.expire(el);
        }
      });
    } else {
      if (Gilt.Notifications.anythingExpiringSoon(true)) {
        Gilt.Notifications.popdown();
      }
    }
    Gilt.Notifications.countdownTimer = setTimeout(Gilt.Notifications.countdown, pollOnSecond ? 1000 - (current_time % 1000) : 5000);
  },
  anythingExpiringSoon: function(exact) {
    if (!Gilt.Notifications.enabled) {
      return false;
    }
    //if (Gilt.Notifications.element.find("#carousel-notifications-current div.carousel-notification-item").length) {
    //  return true;
    //}
    var result = false;
    var test_time = (new Date()).getTime() + (Gilt.Notifications.showSecondsAtNMinutes * 60000);
    Gilt.Notifications.element.find("#carousel-notifications-current div.carousel-notification-item[data-countdownto]").each(function() {
      var item_time = parseInt($(this).attr("data-countdownto"));
      if (item_time <= test_time && (!exact || item_time >= test_time - 6000)) {
        result = true;
        return false;
      }
    });
    return result;
  },
  test: {
    countdown_soon: function() {
      Gilt.Notifications.add({k:"countdown",v:["Testing", "#", "Countdown for @@time@@", "Countdown complete", "", "#", (new Date()).getTime() + 180000], r: (new Date()).getTime() + 240000});
    },
    countdown_immediate: function() {
      Gilt.Notifications.add({k:"countdown",v:["Testing", "#", "Countdown for @@time@@", "Countdown complete", "", "#", (new Date()).getTime() + 120000], r: (new Date()).getTime() + 180000});
    },
    expired: function() {
      Gilt.Notifications.expire(Gilt.Notifications.add({k:"basic",v:["Testing","Simple","Notification"]}));
    },
    clear: function() {
      $("div.carousel-notification-item:not(div.carousel-notification-permanent-item)").each(function() {
        Gilt.Notifications.remove($(this));
      });
    }
  },
  templates: {
    basic: function(subtitle, inner, action) {
      return $("<div class='carousel-notification-item'><a href='#' class='subtitle'></a>&nbsp;<span></span>&nbsp;<a href='#' class='action'></a></div>")
        .find("a.subtitle")
          .iff(subtitle)
            .text(subtitle)
          .others()
            .remove()
          .end()
        .end()
        .find("span")
          .iff(inner)
            .text(inner)
          .others()
            .remove()
          .end()
        .end()
        .find("a.action")
          .iff(action)
            .text(action)
          .others()
            .remove()
          .end()
        .end();
    },
    basic_with_events: function(subtitleText, subtitleEvent, innerText, actionText, actionEvent) {
      var exists = function(path, context) {
        if (!$.isArray(path)) {
          path = path.split(/\./g);
        }
        if (!context) {
          context = window;
        }
        if (($.isFunction(context.hasOwnProperty) && context.hasOwnProperty(path[0])) || context[path[0]]) { // window object in IE doesn't support hasOwnProperty
          context = context[path.shift()];
          if (!path.length) {
            return context;
          }
          return exists(path, context);
        }
        return false;
      };
      var wrapper = function(event) {
        return function(ev) {
          ev.preventDefault();
          exists(event)(ev);
          //Gilt.Notifications.snooze();
        };
      };
      return Gilt.Notifications.templates.basic(subtitleText, innerText, actionText)
        .find("a.subtitle")
          .iff($.isFunction(subtitleEvent))
            .click(subtitleEvent)
          .others()
            .attr("href", subtitleEvent)
          .end()
        .end()
        .find("a.action")
          .iff(exists, actionEvent)
            //.tap(function() { console.debug(this); })
            .click(wrapper(actionEvent))
          .others()
            .attr("href", actionEvent)
          .end()
        .end();
    },
    countdown: function(subtitleText, subtitleEvent, countingDownMessage, countDownCompleteMessage, actionText, actionEvent, countDownTo) {
      return Gilt.Notifications.templates.basic_with_events(subtitleText, subtitleEvent, countingDownMessage.replace("@@time@@", ""), actionText, actionEvent)
        .attr("data-countdownto", countDownTo)
        .attr("data-countdownmessage", countingDownMessage)
        .attr("data-countdowncomplete", countDownCompleteMessage);
    },
    sku: function(skuid, subtitleText, subtitleEvent, countingDownMessage, countDownCompleteMessage, actionText, actionEvent, countDownTo) {
      return Gilt.Notifications.templates.countdown(subtitleText, subtitleEvent, countingDownMessage, countDownCompleteMessage, actionText, actionEvent, countDownTo)
        .attr("data-skuid", skuid);
    },
    sale_start: function(subtitleText, subtitleEvent, innerText, actionText, actionEvent) {
      return Gilt.Notifications.templates.basic_with_events(subtitleText, subtitleEvent, innerText, actionText, actionEvent)
        .find("a:first").switchClass("subtitle", "action").end()
        .find("a:last").switchClass("action", "subtitle").end()
    }
  }
};
var gg;
if (!gg) {
    gg = {};
}

gg.Blackbird = {};

gg.Blackbird.display_form_errors = function(error_id, errors) {
    var html = '<ul>';
    var i = -1;
    var len = errors.length;
    while (++i < len) {
	    html += ' <li> ' + errors[i] + '</li>';
    }
    html += '</ul>';
    $('#' + error_id).html(html);
};

// We have a common base case which is to display a form in rails,
// then submit it via AJAX against blackbird. The blackbird response
// will either contain validation errors which are then displayed to
// the USER or a set of cookies that are set before forwarding the
// user to another URL
//
// Example:
// on_submit = "gg.Blackbird.process_basic_form('/bb/login', '#{@returnURL}', '#{form_id}', '#{error_explanation_id}', '#{form_button_id}'); return false"
// <% form_tag(url_for(...), {:id => form_id, :onSubmit => on_submit}) do -%>
//
// failureFallbackCallback: If the request fails, and you provide this callback,
// we will invoke it with two arguments: form_id and another callback. You can
// then try to handle the failure, and if you fail, just call the blackbird
// callback you received to display the error
//
gg.Blackbird.process_basic_form = function(url, default_target_url, form_id, errors_id, register_button_id, failureFallbackCallback) {
    $.ajax({
        url: url,
        type: 'POST',
        data: $("#"+form_id).serialize(),
        dataType: 'json',
        error: function() {
            if (!failureFallbackCallback) {
                gg.Blackbird.display_form_errors(errors_id, [ Locale.blackbird_form_error ]);
            } else {
                failureFallbackCallback(form_id, function() {
                    gg.Blackbird.display_form_errors(errors_id, [ Locale.blackbird_form_error ]);
                });
            }
        },
        success: function(data) {
            var response = data.response;
            if (response.errors) {
                gg.Blackbird.display_form_errors(errors_id, response.errors);
            } else {
                gg.Blackbird.setCookies(response.cookies);
                var ifs = jQuery.url.param("ifs");  // From ZXTM Rule: req_redirect_login
                if (ifs == null || ifs == "") {
                    target_url = default_target_url;
                } else {
                    target_url = jQuery.url.setUrl("http://www.gilt.com/?" + unescape(ifs)).param("return_url");
                    if (target_url == null) {
                      target_url = default_target_url;
                    }
                }
                window.location = target_url;
            }
        }
    });
};

gg.Blackbird.setCookies = function(cookies) {
    if (cookies) {
        var i = cookies.length;
        while (i--) {
            document.cookie = cookies[i];
        }
    }
};


// Accesses blackbird to refresh the cookies for this user
gg.Blackbird.updateUserCookies = function() {
    if (!fl.Util.readCookie('ca_expiration') && fl.Util.readHashedCookie('guid')) {
        fl.Util.setPersistentCookie('ca_expiration', '1', 3600);
        $.get('/bb/login/refresh_user_cookies', {}, function(data) {
            var response = data.response;
            if (response) {
                gg.Blackbird.setCookies(response.cookies);
                if ("1" == response.changed) {
                    // Cookies have been updated. check if we can
                    // redirect, but be very conservative. We only
                    // care to redirect the /sale urls - if there are
                    // no query parameters, we redirect
                    var url = window.location.toString();
                    if (-1 == url.indexOf('?') && -1 != url.indexOf('/sale')) {
                        window.location = url + '?ucac=1';
                    }
                }
            }
        }, 'json')
    }
};

var gg;
if (!gg) {
    gg = {};
}

gg.Inventory = {};
gg.Inventory.defaultReservationMinutes = 10;

gg.Inventory.common_params = function(product_id) {
    // Use a random string to prevent caching in IE browsers.
    var s = "product_id=" + product_id + "&jskey=" + gg.random_string(20) + "&user_guid=";
    var user_id = fl.Util.readHashedCookie('guid');
    if (user_id) {
        s += user_id;
    }
    s += "&user_guid=";
    var guid = fl.Util.readHashedCookie('guid');
    if (guid) {
        s += guid;
    }
    return s;
};

gg.Inventory.reserve_unit = function(product_id, sku_id, quantity, callback, extra) {
    $.ajax({
        url: '/inventory_service/reserve_units',
        type: 'GET',
        data: gg.Inventory.common_params(product_id) + "&reservation_time=" + gg.Inventory.defaultReservationMinutes + "&sku_id=" + sku_id + "&quantity=" + quantity,
        dataType: 'json',
        error: function(xhr, status, error) {
            log.setup("ajax", "inventory")("error", "Inventory Reserve Unit Error:", xhr, status, error);
            callback(product_id, sku_id, quantity, [], 0);
        },
        success: function(data) {
            var verified_reservations = [];
            var i = -1;
            var max = data.data.reservations.length;
            while (++i < max) {
                if (data.data.reservations[i].sku_id == sku_id || 0 > data.data.reservations[i].sku_id) {
                    verified_reservations[ verified_reservations.length ] = data.data.reservations[i];
                }
            }
	          callback(product_id, sku_id, quantity, verified_reservations, (new Date()).getTime() - (new Date(data.timestamp)).getTime(), extra);
        }
    });
};

// params: unit_id=11138216&11138216=2009-04-09T15%3A36%3A54Z
gg.Inventory.clear_units = function(product_id, params) {
    $.get('/inventory_service/clear_reservations', gg.Inventory.common_params(product_id) + "&" + params);
};

// successCallback -- accept a new reservation. It is your job to check
// for the unit_id which may be -1 (out of stock) or have changed.
gg.Inventory.extend_reservation = function(reservation, failureCallback, successCallback) {
    if (0 > reservation.unit_id) {
        gg.Inventory.reserve_unit(reservation.product_id, reservation.sku_id, 1, function(product_id, sku_id, quantity, reservations, server_clock_delta_millis) {
            if (1 == reservations.length) {
                successCallback(reservations[0]);
            } else {
                failureCallback(reservation);
            }
        });
        return;
    }

    $.ajax({
        url: '/inventory_service/extend_reservation',
        type: 'GET',
        data: gg.Inventory.common_params(reservation.product_id) + "&reservation_time=" + gg.Inventory.defaultReservationMinutes + "&unit_id=" + reservation.unit_id + "&" + reservation.unit_id + "=" + reservation.expiration + "&sku_id=" + reservation.sku_id,
        dataType: 'json',
        error: function(xhr, status, error) {
            log.setup("ajax", "inventory")("error", "Inventory Extend Reservation Error: ", xhr, status, error);
            failureCallback(reservation);
        },
        success: function(data) {
            if (data.data) {
                successCallback(data.data.reservation);
            }
            else {
                failureCallback(reservation);
            }
        }
    });
};

// Requests product status - which looks/skus are in stock.
// Should be cached by Zeus for around 60 seconds.
gg.Inventory.product_status = function(product_id, callback) {
    log.setup("ajax", "inventory")("Requesting Product Status");
    $.ajax({
        url: '/inventory_service/product_status',
        type: 'GET',
        data: { product_id: product_id },
        dataType: 'json',
        error: function(xhr, status, error) {
            log.setup("ajax", "inventory");
            switch (status) {
                case 'parsererror' :
                    log("error", "Inventory Product Status Parser Error: ", xhr.responseText);
                    callback(product_id, null, "Could not parse:" + xhr.responseText);
                    break;
                case 'timeout' :
                    log("error", "Inventory Product Status Timeout");
                    callback(product_id, null, 'timeout');
                    break;
                case 'error' :
                    log("error", "Inventory Product Status Failure:", error);
	                callback(product_id, null, 'error');
                    break;
            }
        },
        success: function(data) {
            log.setup("ajax", "inventory")("Inventory Product Status:", data);
            if (data.data) {
	            callback(product_id, data.data);
            }
            else {
	            callback(product_id, null, data.msg);
            }
	    }
    });
};

// Requests in-stock status for all looks on a sale.
// Should be cached by Zeus.
gg.Inventory.sale_status = function(sale_id, successCallback, errorCallback) {
    $.ajax({
        url: '/inventory_service/sale_summary',
        type: 'GET',
        data: { sale_id: sale_id, jskey: gg.random_string(20) },
        dataType: 'json',
        error: function(xhr, status, error) {
            log.setup("ajax", "inventory")("error", "Inventory Sale Status Error: ", xhr, status, error);
            errorCallback();
        },
        success: function(data) {
            if (data.data) {
	            successCallback(sale_id, data.data);
            }
            else {
                errorCallback();
            }
        }
    });
};

// Javascript library for client side personalization
// Copyright 2007-2008 Gilt Groupe, Inc.
var gg;
if (!gg) {
    gg = {};
}
gg.Usermeta = {};

gg.Usermeta.data = function() {
    return gg.parse_json(fl.Util.readCookie('usermeta'));
};

gg.Usermeta.getValue = function(key) {
  var data = gg.Usermeta.data();
  if (data) {
    return data[key];
  }
  return null;
};

gg.Usermeta.setValue = function(elId, value, doInsertion, defaultValue) {
    log.setup("usermeta");
    if (!value) {
        value = defaultValue;
    }
    if (value || 0 === value) {
        var el = $("#" + elId);
        if (el.length) {
            if (doInsertion) {
                log("Inserting %s after #%s", value, elId);
                el.replaceWith(value);
            } else {
                log("Setting #%s to %s", elId, value);
                el.html(value);
            }
        }
    }
};

gg.Usermeta.init = function() {
    log.setup("startup", "usermeta")("Initializing Usermeta");
    var data = gg.Usermeta.data();
    if (!data){
        log("Did not find Metadata");
        return;
    }

    log("Found User Metadata %o, Continuing...", data);

    if (!gg.Usermeta.isTimeZoneSet) {
        log("Initializing TimeZone");
        gg.Usermeta.setTimeZone($('.tzchange'));
        gg.Usermeta.isTimeZoneSet = true;
    }
    log("Initializing Display Name");
    //gg.Usermeta.setValue('usermeta_display_name', data.display_name, true);
    if (!$("#user").data("username-set")) {
      $("#user")
        .text($("#user").text() + " " + data.display_name)
        .data("username-set", true);
    }
    if ("1" == data.admin_nav_link) {
        log("Initializing Admin Link");
        gg.Usermeta.setValue('usermeta_admin_nav_link', '<a href="/admin/">Admin</a>', false);
    }
    if ("1" == data.warehouse_nav_link) {
        log("Initializing Warehouse Link");
        gg.Usermeta.setValue('usermeta_warehouse_nav_link', '<a href="/warehouse/">Warehouse</a>', false);
    }
    if ("1" == data.bounced) {
        log("Showing Bounce Message");
        var reset_link = "/account/reset_bounces";
        var bounce_message = Locale.bounce_message + '<a href="' + reset_link + '" style="display: inline">' + Locale.click_here + '</a>';
        gg.Usermeta.setValue('usermeta_bounced', bounce_message, false);
        $('#usermeta_bounced').show();
    }
    log("Usermeta Initialization Complete");
};

gg.Usermeta.sale_maybe_add_next_previous_links = function(saleId) {
    var el = $('#sale_next_previous_sales');
    if (!el.length) {
        return;
    }

    var value = fl.Util.readCookie('sale_list');
    if (!value) {
        return null;
    }

    var ids = value.split(' ');
    var i = ids.length;
    while (i--) {
        if (ids[i] == saleId) {
            var content = '';
            if (0 < i) {
                content += "<div id=\"previous_link\"><a href=\"/sale/preview/" + ids[i - 1] + "\">&laquo;&nbsp;Previous Sale</a></div>";
            }
            if (ids.length - 1 > i) {
                content += "<div id=\"next_link\"><a href=\"/sale/preview/" + ids[i + 1] + "\">Next Sale&nbsp;&raquo;</a></div>";
            }
            if (0 < content.length) {
                el.html(content);
            }
            return;
        }
    }
};

gg.Usermeta.sale_maybe_add_next_previous_post_links = function(currentPostId) {
    var el = $('#blog_next_previous_posts');
    if (!el.length) {
        return;
    }

    var value = fl.Util.readCookie('blog_post_list');
    if (!value) {
        return null;
    }

    var info = value.split(' ');
    var i = info.length;
    while (i--) {
        if (info[i] == currentPostId) {
            var content = '';
            if (0 < i) {
                content += "<a href=\"/blog/redirect/" + info[i - 1] + "?s=bpp\" id=\"prev_post_link\"><img src=\"/images/us/blog/left-post-arrow-blue.png\"/>&nbsp;Previous</a>";
            }
            content += "<a href=\"/blog\" id=\"main_index_link\">Back to main page</a>";
            if (info.length - 1 > i) {
                content += "<a href=\"/blog/redirect/" + info[i + 1] + "?s=bpn\" id=\"next_post_link\">Next&nbsp;<img src=\"/images/us/blog/right-post-arrow-blue.png\"/></a>";
            }
            if (0 < content.length) {
                el.html(content);
            }
            return;
        }
    }
};

gg.Usermeta.setTimeZone = function(spans) {
    log.setup("usermeta");

    log("Setting TimeZone to %s(%d)");
    var tzregex = /(\: *\d{2} *)([a-z]+)([\-\+]\d+)? *\(?([a-z ]+)?/i;
    var tzreplace = /[a-z() ]/g;

    spans.each(function(i, s) {
        var dateformat = $(s).attr('dateformat');
        var localdate = new Date();

        localdate.setTime(Date.parse($(s).html()));
        var tzname = localdate.toString();
        // Opera doesn't give us the local time zone name, but we don't really care.
        tzname = tzregex.exec(tzname) || [];
        if(!tzname[3]) tzname[4] = tzname[2];
        if(tzname[4]){
          tzname = tzname[4];
        } else {
          tzname = tzname[2] + tzname[3];
        }
        tzname = tzname.replace(tzreplace,"");
        var day = localdate.getDay();
        var day_date = localdate.getDate();
        var month = localdate.getMonth() + 1;
        var hours = localdate.getHours();
        var year = localdate.getYear() + 1900;

        var meridian = '';
        if (0 == hours) {
            hours = 'MIDNIGHT';
        } else if (12 == hours) {
            hours = 'NOON';
        } else if (12 < hours) {
            hours -= 12;
            meridian = 'PM';
        } else if (12 > hours) {
            meridian = 'AM';
        }
        switch(day) {
            case 0: day = 'Sunday'; break;
            case 1: day = 'Monday'; break;
            case 2: day = 'Tuesday'; break;
            case 3: day = 'Wednesday'; break;
            case 4: day = 'Thursday'; break;
            case 5: day = 'Friday'; break;
            case 6: day = 'Saturday'; break;
        }
        dateformat = dateformat.replace(/\%I/g, hours);
        dateformat = dateformat.replace(/\%p/g, meridian);
        dateformat = dateformat.replace(/\%m/g, month);
        dateformat = dateformat.replace(/\%Y/g, year);
        if (10 > day_date) {
            day_date = ' ' + day_date;
        }
        dateformat = dateformat.replace(/\%e/g, day_date);
        dateformat = dateformat.replace(/\%A/g, day);
        dateformat = dateformat.replace(/\%z/g, tzname);
        $(s).html(dateformat).show();
    });
};

gg.Usermeta.updateCartItemCountDirect = function(number_items) {
    gg.Usermeta.setValue('carousel-nav-cart span', "(" + number_items + ")", false, 0);
    gg.Cart.itemExpirationHeader(gg.Cart.current);
};


// Javascript Product Library
// Copyright 2007-2008 Gilt Groupe, Inc.
var gg;
if (!gg) {
    gg = {};
}
gg.Pca = {};
gg.Gender = {};

gg.Gender.cookieRead = false;
gg.Gender.value = null;

gg.Gender.getValue = function(index) { // TODO: I don't see anyplace where we're setting this cookie.  I do however see a "gender" cookie, and a gender in the usermeta cookie
    if (!gg.Gender.cookieRead) {
        gg.Gender.cookieRead = true;
        gg.Gender.value = fl.Util.readCookie('pca');
        if (gg.Gender.value) {
            gg.Gender.value = gg.Gender.value.split('.');
        }
    }

    if (!gg.Gender.value) {
        return null;
    }

    return gg.Gender.value[0];
};

// Swaps in an image based on the currently set gender cookie.
gg.Gender.select_image = function(elId, male_path, female_path, default_path) {
    var gender = gg.Gender.getValue();
    var el = $('#' + elId);
    if (!el.length) {
        return;
    }

    switch(gender) {
        case 'm':
            el.attr("src", male_path);
            break;
        case 'f':
            el.attr("src", female_path);
            break;
        default:
            el.attr("src", default_path);
    }
};

var fl;
if (!fl.Formatter) {
    fl.Formatter = {};
}

fl.Formatter.address_city_formatter = function(city_field, state_field, state_value) {
    fl.Formatter.capitalize(city_field);
    var value = city_field.value;
    if ("Apo" == value || "APO" == value || "Fpo" == value || "FPO" == value) {
        $("#"+state_field).val(state_value);
    }
};

fl.Formatter.lastElement = null;
fl.Formatter.lastLastElement = null;
fl.Formatter.capitalize = function(elOrId) {
    var el = $(elOrId)||$("#"+elOrId);
    if (el == fl.Formatter.lastLastElement) {
        return;
    }
    fl.Formatter.lastLastElement = fl.Formatter.lastElement;
    fl.Formatter.lastElement = el;
    el.val(fl.Formatter.capitalizeString(el.val()));
};

fl.Formatter.capitalizeString = function(string) {
    var final_string = "";
    var els = string.split(" ");
    var i = -1;
    var max = els.length;
    while (++i < max) {
        final_string += " " + els[i].charAt(0).toUpperCase() + els[i].substr(1);
    }
    return final_string.substring(1);
};

// Formats a credit card number by putting in spaces after every
// 4th digit in a 16 digit card number
fl.Formatter.creditCard = function(el) {
    log.setup("formatter")("Formatting %s as a Credit Card", el.value);
    var str = $(el).val();
    if (fl.Util.IsEmpty(str)) {
        return true;
    }
    str = str.replace(fl.Formatter.creditCard.strip, '');
    if (fl.Validate.IsInteger(str)) {
        if (16 == str.length){
            str = str.replace(fl.Formatter.creditCard.visa_mc, "$1 $2 $3 $4");
        } else if (15 == str.length) {
            str = str.replace(fl.Formatter.creditCard.amex, "$1 $2 $3");
        } else if (13 == str.length) {
            str = str.replace(fl.Formatter.creditCard.error, "$1 $2 $3 $4 $5");
        }
        $(el).val(str);
    }
    log("Result: ", $(el).val());
    return true;
};
fl.Formatter.creditCard.strip = /[^\d]/g;
fl.Formatter.creditCard.visa_mc = /(\d{4})(\d{4})(\d{4})(\d{4})/;
fl.Formatter.creditCard.amex = /(\d{4})(\d{6})(\d{5})/;
fl.Formatter.creditCard.error = /(\d)(\d{3})(\d{3})(\d{3})(\d{3})/;
fl.Formatter.creditCardAsYouType = function(element) {
  $(element).keyup(function(ev) {
    if (48 <= ev.keyCode && 57 >= ev.keyCode) {
      var value = $(this).val().replace(/\D/g, "");
      var cclength = 16;
      var grouping = /(.{4})(.{4})(.{4})(.{4})/;
      var replace = "$1 $2 $3 $4";
      // /^(51|52|53|54|55|4|6011|3)/ // mastercard, visa, discover, and jcb16
      if (/^(34|37|2131|1800)/.test(value)) { // amex and jcb15
        cclength = 15;
        grouping = /(.{4})(.{6})(.{5})/;
        replace = "$1 $2 $3";
      } else if (/^(4222222222222)/.test(value)) { // error code test card number
        cclength = 13;
        grouping = /(.)(.{3})(.{3})(.{3})(.{3})/;
        replace = "$1 $2 $3 $4 $5";
      }
      for (var i = value.length; i < cclength; i++) {
        value += "*";
      }
      value = value.replace(grouping, replace);
      if (8 != ev.keyCode && 46 != ev.keyCode) {
        var c = $(this).caret();
        var len = $(this).val().length;
        $(this).val(value.replace(/\*+\s?/g, ""));
        if (c < len) {
          $(this).caret(c);
        }
      }
    } else {
      $(this).val($.trim($(this).val()));
      //$(this).val($(this).val().replace(/^\s*/, "").replace(/\s*$/, ""));
    }
  });
};

fl.Formatter.commify = function (num) {
    return num.toString().replace(fl.Formatter.currency.group, Locale.currency_group_delimiter + "$1");
};

// Formats number into currency
fl.Formatter.currency = function (num, show_cents) {
    log.setup("formatter")("Formatting %s as Currency", num);
    var isNegative = false;
    num = num.toString().replace(Locale.currency_symbol, '').replace(fl.Formatter.currency.strip, "$1");
    if (isNaN(num)) {
        num = "0";
    }
    if (0 > num) {
    num = Math.abs(num);
        isNegative = true;
    }
    var cents = Math.floor((num * 100 + 0.5) % 100);
    num = Math.floor((num * 100 + 0.5) / 100).toString();
    if (10 > cents) {
        cents = "0" + cents;
    }
    log("%d dollars and %d cents", num, cents);
    log("Grouping");
    num = fl.Formatter.commify(num);
    var result;
    if (!show_cents && "00" == cents) {
      result = Locale.currency_symbol + num;
    } else {
      result = Locale.currency_symbol + num + Locale.currency_decimal_point + cents;
    }
    if (isNegative) {
        result = "-" + result;
    }
    log("Result: ", result);
    return result;
};
fl.Formatter.currency.strip = /[,](\d\d\d)/g; // strips out commas <s>and periods</s> only if they're used for grouping, not decimal point
fl.Formatter.currency.group = /(?!^)(\d{3})(?=(\d{3})*$)/g; // matches in groups of three, starting at the end

fl.Formatter.phone = function(elOrId) {
    var el = $(elOrId)||$("#"+elOrId);
    el.val(fl.Formatter.phone_string(el.val()));
};

fl.Formatter.phone_string = function(ov) {
    log.setup("formatter")("Formatting %s as a Phone Number", ov);

    log("Checking for escaped (+) phone number, and removing leading 1");
    var v = ov.replace(fl.Formatter.phone_string.strip, '').match(fl.Formatter.phone_string.check);
    if (v) {
        log("Grouping digits");
        v = v[1].replace(fl.Formatter.phone_string.group, "($1) $2-$3 x$4").replace(fl.Formatter.phone_string.del_ext, '');
        log("Result: ", v);
        return v;
    }
    log("Invalid Phone Number");
    return '';
};
fl.Formatter.phone_string.strip = /[^+\d]/g; // remove all non-digits except +
fl.Formatter.phone_string.check = /^(?=[^+])1?(\d*)/; // returns null if first character is a +, else, strips leading 1 and returns remainder at index 1
fl.Formatter.phone_string.group = /(\d{3})(\d{3})(\d{4})(\d*)/;
fl.Formatter.phone_string.del_ext = / x$/; // if there is no extension (string ends in " x"), remove the " x"

fl.Formatter.phoneNumberAsYouType = function(element) {
  $(element).keyup(function(ev) {
    if (48 <= ev.keyCode && 57 >= ev.keyCode) {
      var value = $(this).val()
        .replace(/[^\d+]/g, "")
        .replace(/(\+?)(1?)(\d{0,3})(\d{0,3})(\d{0,4})(\d*)/, "$1$2 ($3) $4-$5 x$6")
        .replace(/ x$/g, "")
        .replace(/ ?\-$/, "")
        .replace(/\)$/, "")
        .replace(/\($/, "")
        .replace(/\((\d\d\d)$/, "($1)")
        .replace(/\ (\d\d\d)$/, " $1-")
        .replace(/^ /, "");
      var c = $(this).caret();
      var len = $(this).val().length;
      $(this).val(value);
      if (c < len) {
        $(this).caret(c);
      }
    }
  });
};

fl.Formatter.shipping_address_street = function(el, maxLength, divId) {
    var value = el.value;
    if (value && value.length >= maxLength) {
        $("#"+divId).html(Locale.shipping_address_street_length_message(maxLength));
    } else {
        $("#"+divId).html('');
    }
};

fl.Formatter.businessDaysSince = function(days, date) {
  date = date || new Date();
  var milliseconds_in_a_day = 86400000; // 1000 * 60 * 60 * 24
  var result = date.getTime();
  var result_date = new Date();
  result_date.setTime(result);
  for (i = 0; i < days; i++) {
    result += milliseconds_in_a_day;
    result_date.setTime(result);
    while ((result_date.getDay() == 0) || (result_date.getDay() == 6)) {
      result += milliseconds_in_a_day;
      result_date.setTime(result);
    }
  }
  return result_date;
};

fl.Formatter.replaceBusinessDayRangeWithDates = function(range, date) {
  if (!range) {
    return '';
  }

  date = date || new Date();
  var rangePattern = /(\d+) to (\d+) business days/;

  if (!range.match(rangePattern)) {
    return range;
  }
  var earliestDay  = RegExp.$1;
  var latestDay    = RegExp.$2;
  var earliestDate = fl.Formatter.businessDaysSince(earliestDay, date);
  var latestDate   = fl.Formatter.businessDaysSince(latestDay, date);

  var dates = fl.Formatter.stripLeadingZero($.strftime("%a %m/%d/%y", earliestDate)) +
              " to " +
              fl.Formatter.stripLeadingZero($.strftime("%a %m/%d/%y", latestDate));

  return range.replace(rangePattern, "<nobr>" + dates + "</nobr>");
};

fl.Formatter.stripLeadingZero = function(string) {
  return string.replace(/0(\d)\//g, '$1/');
}

fl.Formatter.convertShippingRangeElements = function() {
  $.each($('.shipping_range'), function(i, element) {
    element = $(element);
    var convertedShippingWindow = fl.Formatter.replaceBusinessDayRangeWithDates(element.html());
    element.html(convertedShippingWindow);
  });
};
// Copyright 2007-2008 Gilt Groupe, Inc.

// Use the rotator to crossfade elements on a page with class "rotator_item"
// that are positioned absolutely on top of each other. Attach the javascript
// functions gg.Rotator.nextItemClick() and gg.Rotator.prevItemClick() to mouse
// click events to advance or retreat the featured element.

var gg;
if (!gg) {
  gg = {};
}
if (!gg.Rotator) {
  gg.Rotator = {};
}


gg.Rotator.init = function() {
  log.setup("startup", "rotator")("Initializing Rotators");
  var gr = gg.Rotator;
  clearTimeout(gr.timer);
  gr.timerInterval = 5000;
  gr.upcomingSaleTimerWaitAfterClickInterval = 10000;
  gr.active = true;
  gr.clickEnabled = true;
  gr.items = $('.rotator_item');
  gr.currentItem = gr.items.eq(0);
  log("Found %d items to rotate through", gr.items.length);
  if (1 < gr.items.length) {
    gr.timer = setTimeout(gr.nextItem, gr.timerInterval);
  }
};

gg.Rotator.swapItem = function(swap) {
  log.setup("rotator")("Executing Parallel Effect");
  gg.Rotator.clickEnabled = false;
  gg.Rotator.currentItem.fadeOut("slow");
  swap.fadeIn("slow", function() {
    gg.Rotator.clickEnabled = true;
  });
  gg.Rotator.currentItem = swap;
};

gg.Rotator.nextItemClick = function() {
  log.setup("interaction", "rotator")("Skipping to next Rotator item");
  gg.Rotator.deactivate();
  if (gg.Rotator.clickEnabled) {
    gg.Rotator.swapNext();
  }
  gg.Rotator.activate();
};

gg.Rotator.prevItemClick = function() {
  log.setup("interaction", "rotator")("Skipping to previous Rotator item");
  gg.Rotator.deactivate();
  if (gg.Rotator.clickEnabled) {
    gg.Rotator.swapPrev();
  }
  gg.Rotator.activate();
};

gg.Rotator.swapNext = function() {
  log.setup("rotator")("Swapping next Rotator item");
  if (1 < gg.Rotator.items.length) {
    var next = gg.Rotator.currentItem.next(".rotator_item");
    if (!next.length) {
        next = gg.Rotator.items.filter(":first");
    }
    gg.Rotator.swapItem(next);
  }
};

gg.Rotator.swapPrev = function() {
  log.setup("rotator")("Swapping previous Rotator item");
  if (1 < gg.Rotator.items.length) {
    var prev = gg.Rotator.currentItem.prev(".rotator_item");
    if (!prev.length) {
        prev = gg.Rotator.items.filter(":last");
    }
    gg.Rotator.swapItem(prev);
  }
};

gg.Rotator.nextItem = function() {
  if (gg.Rotator.active) {
    gg.Rotator.swapNext();
    gg.Rotator.timer = setTimeout(gg.Rotator.nextItem, gg.Rotator.timerInterval);
  } else {
    log.setup("rotator")("Re-enabling Rotator");
    gg.Rotator.active = true;
    gg.Rotator.timer = setTimeout(gg.Rotator.nextItem, gg.Rotator.timerInterval);
  }
};

gg.Rotator.deactivate = function() {
  log.setup("rotator")("Deactivating Rotator");
  clearTimeout(gg.Rotator.timer);
  gg.Rotator.active = false;
};

gg.Rotator.activate = function() {
  log.setup("rotator")("Reactivating Rotator");
  gg.Rotator.active = true;
  gg.Rotator.timer = setTimeout(gg.Rotator.nextItem, gg.Rotator.timerInterval);
};

gg.Rotator.toggleActive = function() {
  if (gg.Rotator.active){
    gg.Rotator.deactivate();
  }else{
    gg.Rotator.activate();
  }
};

// Javascript Product Library
// Copyright 2007 Gilt Groupe, Inc.
var fl;
if (!fl) {
    fl = {};
}

fl.Product = {};
// -- Metadata for the images --
fl.Product.MetaImage = {
    seriesCache: {},
    selectedSeriesId: "0",
    saleId: null,
    productId: null,
    blackbird: false,
    serverSideCart: false,
    selectedColorId: null,
    zoomInfo: null,
    bodyElement: null,
    isConfigured: false,
    selectedLookId: null,

    // setBuyNowOpacity is here as a hook to fade in / out the buy now
    // button. I've disabled it in Jan 2008 as we want the button to
    // always be black.
    setBuyNowOpacity: function() {},
    enable_blackbird: function() {
        log.setup("product")("Enabling Blackbird");
        fl.Product.MetaImage.blackbird = true;
    },
    enableServerSideCart: function() {
        log.setup("product")("Enabling server-side cart");
        fl.Product.MetaImage.serverSideCart = true;
    },
    configure: function(saleId, productId, mainPhotoDivId, zoomPhotoDivId, zoomFactor, thumbDivId, defaultColorId) {
        log.setup("startup", "product")("Initializing Metadata for Product Images");
        fl.Product.MetaImage.saleId = saleId;
        fl.Product.MetaImage.productId = productId;
        fl.Product.MetaImage.mainPhotoDivElement = function() {
            return $("#" + mainPhotoDivId);
        };
        fl.Product.MetaImage.thumbDivElement = function(seriesId) {
            return $("#" + thumbDivId + seriesId);
        };
        fl.Product.MetaImage.selectedColorId = defaultColorId;
        fl.Product.MetaImage.zoomInfo = {
            photoDivId: zoomPhotoDivId,
            zoomFactor: zoomFactor,
	        priorZoomedImage: null
        };
        fl.Product.MetaImage.bodyElement = document.getElementsByTagName("body")[0];
        fl.Product.MetaImage.isConfigured = true;
    },
    createImage: function(path, width, height) {
        log.setup("product")("Creating a Product Image");
        var image = new Image();
        image.src = path;
        image.id = '_fl_' + fl.Util.GetUniqueIndex();
        if (width) {
            image.width = width;
        }
        if (height) {
            image.height = height;
        }
        return image;
    },
    largeImage: {},
    register: function(seriesId, colorId, smPath, smWidth, smHeight, medPath, medWidth, medHeight, lgPath, lgWidth, lgHeight) {
        log.setup("product")("Registering a Series of Images");
        if (!fl.Product.MetaImage.isConfigured) {
            log("error", "You must call fl.Product.MetaImage.configure before register");
            return;
        }
        var seriesHash = fl.Product.MetaImage.seriesCache[seriesId];
        if (!seriesHash) {
            seriesHash = {};
            fl.Product.MetaImage.seriesCache[seriesId] = seriesHash;
        }
        var sm  = fl.Product.MetaImage.createImage(smPath, smWidth, smHeight);
        var med = fl.Product.MetaImage.createImage(medPath, medWidth, medHeight);
        fl.Product.MetaImage.largeImage[smPath] = function() {
            return fl.Product.MetaImage.downloadImage(lgPath, lgWidth, lgHeight);
        };
        seriesHash[colorId] = { sm: sm, med: med };
    },
    start: function() {
        log.setup("product")("Starting Downloading Large Images");
	    //fl.Pointer.BeginCapturing();
        var imgs = fl.Product.MetaImage.largeImage;
        for (var imageKey in imgs) {
            if ("function" == typeof imgs[imageKey]) {
	            imgs[imageKey]();
            }
	    }
    },
    downloadImageCache: {},
    downloadImage: function(path, width, height) {
        log.setup("product")("Downloading Image from %s", path);
        var image = fl.Product.MetaImage.downloadImageCache[path];
        if (!image) {
            image = fl.Product.MetaImage.createImage(path, width, height);
            fl.Product.MetaImage.downloadImageCache[path] = image;
        }
        return image;
    },
    // Primary method to swap out an image for an html element based on the series and color
    swap: function(el, seriesId, colorId, key, hideIfNotFound) {
        log.setup("product")("Swapping Image Series %s", seriesId);
        var o = fl.Product.MetaImage.getImageObject(seriesId, colorId, key);
        if (!o) {
            if (hideIfNotFound) {
                el.attr("src", fl.Init.ImageUri('/images/default/util/blank.gif'));
                el.hide();
            }
        } else if (el.length) {
            if (o.width) {
                el.width(o.width);
            }
            if (o.height) {
                el.height(o.height);
            }
            el.attr("src", o.src);
            el.attr("fullsrc", o.src.replace(/\/sm\./,"/lg."));
            el.show();
        }
    },
    // Gets image path based on series and color. May return null. key is either 'sm' or 'med'
    getImageObject: function(seriesId, colorId, key) {
        var seriesHash = fl.Product.MetaImage.seriesCache[seriesId];
        if (seriesHash) {
            var images = seriesHash[colorId];
            if (images) {
                return images[key];
            }
        }
        return null;
    }
};

// -- Photo Series --
fl.Product.Series = {
    change: function(seriesId, zoom) {
        log.setup("product", "zoom")("Changing Image Series to %s", seriesId);
        fl.Product.MetaImage.swap(fl.Product.MetaImage.mainPhotoDivElement(), seriesId, fl.Product.MetaImage.selectedColorId, 'med');
        fl.Product.Series.persist(seriesId);
        if (zoom) {
            $("#thumb" + seriesId).data("zoomed").src = $("#thumb" + seriesId).attr("fullsrc"); 
            $("#thumb" + seriesId).trigger("zoomstart");
        }
    },
    persist: function(seriesId) {
        fl.Product.MetaImage.selectedSeriesId = seriesId;
    }
};

// -- Photos in Different Colors --
fl.Product.Color = {
    change: function(colorId) {
        log.setup("product")("Changing Color");
        fl.Product.MetaImage.swap(fl.Product.MetaImage.mainPhotoDivElement(), fl.Product.MetaImage.selectedSeriesId, colorId, 'med');
    },
    restore: function() {
        log.setup("product")("Restoring Selected Color");
        fl.Product.Color.change(fl.Product.MetaImage.selectedColorId);
    },
    select: function(colorId, resetValues, productLookId) {
	    if (!resetValues && fl.Product.Inventory.attributes.color.value && fl.Product.Inventory.attributes.color.value == colorId) {
            // no change in color - do nothing. Do not allow members to deselect a color as a
            // color must be selected to proceed through add to cart
            return;
        }
        if (productLookId) {
          fl.Product.MetaImage.selectedLookId = productLookId;
        }
        log.setup("product")("Selecting Color");
        fl.Product.Inventory.selectValue('color', colorId, resetValues);
        fl.Product.Color.persist(fl.Util.unescapeSlashes(colorId));
        var el = fl.Product.Inventory.attributes.color;
        if (el && el.value) {
            if ("default" == el.value) {
                $('.color_select_text').html('<span class="style_subhead">' + Locale.color + ':</span>');
            } else {
                $('.color_select_text').html('<span class="style_subhead">' + Locale.color + ':</span> ' + fl.Util.unescapeSlashes((!el.value.match(fl.Product.Color.default_regex) ? fl.Formatter.capitalizeString(el.value) : fl.Formatter.capitalizeString(el.label))));
            }
        } else {
            $('.color_select_text').html(Locale.select_color);
        }
    },
    persist: function(colorId) {
        fl.Product.MetaImage.selectedColorId = colorId;
        // Change all thumbnails to the selected color
        var cache = fl.Product.MetaImage.seriesCache;
        for (var seriesId in cache) {
            if (cache.hasOwnProperty(seriesId)) {
                var el = fl.Product.MetaImage.thumbDivElement(seriesId);
                if (el) {
                    fl.Product.MetaImage.swap(el, seriesId, colorId, 'sm', true);
                }
            }
        }
        fl.Product.Series.change(fl.Product.MetaImage.selectedSeriesId);
        fl.ImageRollover.init();
    }
};
fl.Product.Color.default_regex=/default|0/;

// Inventory Management
fl.Product.Inventory = {
    attributes: {},
    attribute_pricing: {},
    sku_data: {},
    find_skus_cache: {},
    numberAttributes: 0,
    // value will be null unless the attribute has only one possible value
    // Pricing may change based on color
    registerAttribute: function(key, label, value, msrp_price, sale_price) {
        log.setup("product")("Registering Attribute for key: %s", key);
        fl.Product.Inventory.attributes[key] = {
            key:   key,
            label: label,
            value: value
        };
        fl.Product.Inventory.attribute_pricing[key + ":" + label] = {
            sale_price: sale_price,
            msrp_price: msrp_price
        };
        fl.Product.Inventory.numberAttributes = fl.Product.Inventory.numberAttributes + 1;
        if (1 < fl.Product.Inventory.numberAttributes) {
            // We have more than one attribute option - fade out buy
            // now until user selects all attributes.
            fl.Product.MetaImage.setBuyNowOpacity(50);
        }
        /*
      	var el = $(key + label);
        fl.BubbleToolTip.Prepare(el, fl.Formatter.capitalizeString(key) + ' ' + label + ' is sold out. To get notified if it becomes available please click the Wait List link on the right.', {
            when: function() {
            		return el.hasClass('attrsoldout');
            }
        });
        */
    },
    _allAttributes: null,// never gets set??
    // Cache list of attributes.
    allAttributes: function() {
        log.setup("product")("Retrieving List of all Attributes");
        var _allAttributes = fl.Product.Inventory._allAttributes;
        if (!_allAttributes) {
            _allAttributes = [];
            var attrs = fl.Product.Inventory.attributes;
            for (var attr in attrs) {
                if (attrs.hasOwnProperty(attr)) {
                    _allAttributes[ _allAttributes.length ] = fl.Product.Inventory.attributes[attr];
                }
            }
        }
        return _allAttributes;
    },
    allSkus: [],
    // Note pricing may change based on individual sku
    registerSku: function(saleId, skuId, productId, colorId, sizeId, msrp_price, sale_price, label, numeric_sale_price, shipping_surcharge, details_url, image_url, in_stock, product_look_id) {
        log.setup("product")("Registering SKU: %s", skuId);
        fl.Product.Inventory.allSkus[fl.Product.Inventory.allSkus.length] = {
            id: skuId,
            color: colorId,
            size: sizeId
        };
        fl.Product.Inventory.sku_data[skuId] = {
            sale_id: saleId,
            product_id: productId,
            product_look_id: product_look_id,
            sale_price: sale_price,
            msrp_price: msrp_price,
            numeric_sale_price: numeric_sale_price,
            shipping_surcharge: shipping_surcharge,
            label: label,
            details_url: details_url,
            image_url: image_url,
            in_stock: in_stock
        };
    },
    element: function(key, value) {
        //return $("[id=" + key + value + "]"); // unusual syntax because value sometimes has spaces, which jquery misinterprets
        return $("#" + key + value.replace(/ /g, "\\ ").replace(/\./g, "\\."));
    },

    findSkus: function(listOfAttributes) {
        log.setup("product", "findSkus")("Searching for SKUs that match Attributes:", listOfAttributes);

        var matchingSkus = [];
        var skus = fl.Product.Inventory.allSkus;
        var i = -1;
        var max = skus.length;
        while (++i<max) {
            var sku=skus[i];
            if (!fl.Product.Inventory.sku_data[sku.id] || fl.Product.Inventory.sku_data[sku.id].in_stock) {
                var matches = true;
                var j = listOfAttributes.length;
                while (j--) {
                    var o = listOfAttributes[j];
                    if (sku[o.key] != o.value ){
                        matches = false;
                        break;
                    }
                }
                if (matches) {
                    log.setup("product")("SKU %o matches", sku);
                    matchingSkus[ matchingSkus.length ] = sku;
                }
            }
        }
        fl.Product.Inventory.find_skus_cache[listOfAttributes] = matchingSkus; // TODO: if this doesn't need to be set to [], can change the break above to a return
        return matchingSkus;
    },
    // Returns true if in stock. False otherwise
    checkStock: function(key, value) {
        return !fl.Product.Inventory.element(key, value).hasClass("attrsoldout");
    },
    adjust_pricing: function(pricing) {
        if (pricing) {
            if (pricing.sale_price) {
                $('#buy_product_sale_price').html(pricing.sale_price);
            }
            if (pricing.msrp_price) {
                $('#buy_product_msrp_price').html(pricing.msrp_price);
            }
        }
    },
    // Supports both selecting a particular value and deselecting it.
    // resetValues if set to 0 explicity, means we won't modify any
    // existing css attributes. Used to initialize default colors on
    // page load.
    selectValue: function(key, value, resetValues) {
        log.setup("product")("Selecting Value");
        if (!fl.Product.Inventory.checkStock(key, value)) {
            // Not in stock - cannot select
            return false;
        }
        var attribute = fl.Product.Inventory.attributes[key];
        if (!attribute) { return false; }
        if ("0" == resetValues) {
            attribute.value = value;
        } else {
            $("dd.attr" + key).removeClass('attrselected');
            if (attribute.value == value) {
                attribute.value = null;
            } else {
                attribute.value = value;
                fl.Product.Inventory.element(key, value).addClass("attrselected");
            }
        }

        // Update inventory for each of the attribute rows
        var mainAttributes = fl.Product.Inventory.allAttributes();
        var i = mainAttributes.length;
        while (i--) {
            var mainAttribute = mainAttributes[i];
            log("Updating Inventory for ", mainAttribute.key);
            var selected = [];
            var j = -1;
            var max = mainAttributes.length;
            while (++j < max) { // Does order matter?
                var attr = mainAttributes[j];
                if (attr.value && attr.key != mainAttribute.key){
                    selected[selected.length] = attr;
                }
            }
            var availableSkus = fl.Product.Inventory.findSkus(selected);
            // Now build up a list of all attribute IDs that have at least one SKU
            var availableAttributeIDs = [];
            j = -1;
            max = availableSkus.length;
            while (++j < max) { // Does order matter?
                availableAttributeIDs.push(availableSkus[j][ mainAttribute.key ]);
            }

            availableAttributeIDs = $.uniq(availableAttributeIDs);
            var soldOutItems = {};
            var dds = $("dd.attr" + mainAttribute.key);
            j = dds.length;
            while (j--) {
                soldOutItems[dds.eq(j).id()] = dds.eq(j);
            }
            j = availableAttributeIDs.length;
            while (j--) {
                var el = fl.Product.Inventory.element(mainAttribute.key, availableAttributeIDs[j]);
                if (el.length) {
                    delete soldOutItems[el.id()];
                    el.removeClass('attrsoldout')
                        .find("img:first")
                            .css({ opacity: 1 });
                }
            }
            for (j in soldOutItems) {
                if (soldOutItems.hasOwnProperty(j)) {
                    el = soldOutItems[j];
                    if (!el.hasClass('attrsoldout')) {
                        el.addClass('attrsoldout')
                            .find("img:first")
                                .css({ opacity: 0.45 });
                    }
                }
            }
        }
        fl.Product.MetaImage.setBuyNowOpacity();

        var skus = fl.Product.Inventory.findSelectedSkus();

        // If pricing is specified for this look or sku, update the
        // pricing information shown on the screen

        if (1 == skus.length) {
            fl.Product.Inventory.adjust_pricing(fl.Product.Inventory.sku_data[skus[0].id]);
        } else {
            fl.Product.Inventory.adjust_pricing(fl.Product.Inventory.attribute_pricing[key + ":" + value]);
        }

        if ($("dd.attrsize:first").data("qtip")) {
            $("dd.attrsize:not(.attrsoldout), dd.attrcolor:not(.attrsoldout)").qtip("disable");
            $("dd.attrsize.attrsoldout, dd.attrcolor.attrsoldout").qtip("enable");
        }
    },
    findSelectedSkus: function() {
        log.setup("product")("Searching for a list of SKUs");
        var selected = [];
        var attrs = fl.Product.Inventory.allAttributes();
        var max = attrs.length;
        var i = -1;
        while (++i < max) {
            if (attrs[i].value){
                selected[selected.length] = attrs[i];
            }
        }
        return fl.Product.Inventory.findSkus(selected);
    },
    maybeSubmitForm: function(errorId) {
        log.setup("product")("Testing if the form should be submitted");
        if ( fl.Product.Inventory.maybeDisplayValidationMessage(errorId) ) {
            return false;
        }
        // alert("selected: " + selected);
        var availableSkus = fl.Product.Inventory.findSelectedSkus();
        if (!availableSkus.length) {
            // Sku not found
            $("#" + errorId).show().html("Sold Out");
            return false;
        }
        log("Found skus:", availableSkus);
        $("#" + errorId).hide().html("");
        // NON XHR:
        // $(fieldId).value = availableSkus[0].id;
        // return true;

        var skuId = availableSkus[0].id;
        if (skuId) {
            if (fl.Product.MetaImage.blackbird) {
                var cart = gg.Cart.retrieve();
                if (cart.reservations.length >= gg.Cart.MAX_SIZE) {
                    gg.Cart.display(cart, Locale.max_cart_size(gg.Cart.MAX_SIZE));
                }
                else {
                    // throttle add-to-cart by sku.
                    if (!fl.Product.Inventory.skuThrottle) {
                        fl.Product.Inventory.skuThrottle = {};
                    }
                    var last_add = fl.Product.Inventory.skuThrottle[skuId];
                    if (!last_add || 3000 < (new Date()).getTime() - last_add) {
                        log("Submitting Blackbird Form");
                        fl.Product.Inventory.submitBlackbirdForm(skuId);
                        fl.Product.Inventory.skuThrottle[skuId] = (new Date()).getTime();
                    }
                }
            }
            else if (fl.Product.MetaImage.serverSideCart) {
                // throttle add-to-cart by sku.
                if (!fl.Product.Inventory.skuThrottle) {
                    fl.Product.Inventory.skuThrottle = {};
                }
                last_add = fl.Product.Inventory.skuThrottle[skuId];
                if (!last_add || 3000 < (new Date()).getTime() - last_add) {
                    log("Adding sku to server-side cart");
                    gg.Cart.addSku(fl.Product.MetaImage.saleId, fl.Product.Inventory.sku_data[skuId].product_id, skuId);
                }
            }
            else {
                log("Submitting without using Blackbird");
                fl.Product.Inventory.submitForm(skuId);
            }
        }
        return false;  //  prevent normal form submission
    },
    submitBlackbirdForm: function(sku_id) {
        gg.Cart.showDialog(Locale.your_cart);
        gg.Inventory.reserve_unit(fl.Product.MetaImage.productId, sku_id, 1, fl.Product.Inventory.submitBlackbirdFormResponse);
    },
    submitBlackbirdFormResponse: function(product_id, sku_id, quantity, reservations, server_clock_delta_millis, flags) {
        if (!reservations) {
            return;
        }

        fl.Omniture.initialize('cart', 'cart: add');
        fl.Omniture.addAttribute('products', ';' + sku_id);

        var reservation = reservations[0];
        var sku = fl.Product.Inventory.sku_data[sku_id];
        var cart_box = $("#dialog_cart");
        if (!reservation || 0 > reservation.unit_id) { // TODO: is this test backwards? if exists and, instead of if !exists or
            if (fl.Product.Inventory.waitListEnabled) {
                // Item is unavailable - redirect to wait list modal
                if (!reservation.stat || "R" == reservation.stat) { // TODO: should we test for !reservation?
                    gg.WaitList.initializeForm( Locale.is_not_available, sku_id, 'not_available', '', true );
                } else {
                    gg.WaitList.initializeForm( Locale.is_out_of_stock(sku.label), sku_id, 'out_of_stock', '', true );
                }
            } else {
                if (!reservation.stat || "R" == reservation.stat){
                    cart_box.html('<div style="padding: 15px 15px 5px;"><p>' + Locale.is_not_available + '</p></div>');
                } else {
                    cart_box.html('<div style="padding: 15px 15px 5px;"><p>' + Locale.is_out_of_stock(sku.label) + '</p></div>');
                }
            }
            fl.Omniture.addAttribute('events', 'event6');
            gg.TrackLog.record('add_to_cart', { sku_id: sku_id, sale_id: sku.sale_id, st: 0 });
        } else {
            // Set flash on result of operation
            var cart = gg.Cart.retrieve();
            if (!cart.reservations.length) {
                fl.Omniture.addAttribute('events', 'scOpen');
            }
            else {
                // do we already have this unit?  It can happen.
                var i = -1;
                var max = cart.reservations.length;
                while (++i < max) { // might be able to iterate in reverse
                    if (cart.reservations[i].unit_id == reservation.unit_id) {
                        cart.reservations[i].expiration = reservation.expiration;
                        if (flags && flags.do_not_try_again) {
                            cart_box.html('<div style="padding: 15px 15px 5px;"><p>' + Locale.is_out_of_stock(sku.label) + '</p></div>');
                        }
                        else {
                            gg.Inventory.reserve_unit(product_id, sku_id, 1, fl.Product.Inventory.submitBlackbirdFormResponse, { do_not_try_again: true });
                        }
                        gg.Cart.persist(cart);
                        gg.Cart.refresh(cart);
                        return;
                    }
                }
            }
            if (cart.useEmployeePrices) {
                // flag that we should load details for this new item from the server -- that way we fetch the employee price.
                product_id = null;
                cart.loaded = false;
            }
            if (gg.Cart.addReservation(cart, sku.sale_id, sku_id, product_id, reservation.unit_id, reservation.expiration, sku.label, sku.numeric_sale_price, sku.shipping_surcharge, sku.details_url, sku.image_url, server_clock_delta_millis)) {
                gg.Cart.setUserMessage(cart, null);
                fl.Omniture.addAttribute('events', 'scAdd');
            } else {
                gg.Cart.setUserMessage(cart, Locale.max_cart_size(gg.Cart.MAX_SIZE));
                fl.Omniture.addAttribute('events', 'event7');
            }
            gg.Cart.persist(cart);
            gg.Cart.refresh(cart);
            gg.TrackLog.record('add_to_cart', { sku_id: sku_id, sale_id: sku.sale_id, st: 1 });
        }
        fl.Omniture.doTracking();
    },
    // Submits form via AJAX
    submitForm: function(sku_id) {
        $('#button_buynow').val(sku_id);

        var params = 'sale_id=' + fl.Product.MetaImage.saleId + '&sku_id=' + sku_id
        var el = $('#wait_list_item_id');
        if (el.length) {
            params += '&wait_list_item_id=' + el[0].value;
        }
        gg.Cart.showDialog(Locale.your_cart);
        $("#dialog_cart").load('/cart/add', params, gg.Usermeta.updateCartItemCount);
    },
    maybeDisplayValidationMessage: function(errorId, defaultMessage) {
        log.setup("product")("Testing to maybe display a validation message", errorId);
        var message = defaultMessage;
        if (!message) {
            message = fl.Product.Inventory.missingAttributes();
            if (!message) {
                log("No Message");
                $("#" + errorId).hide().html("");
                return false;
            }
            log("Missing Attributes: ", message);
            message = Locale.please_select(fl.Product.Inventory.localeValue(message));
            log("Inventory Message: ", message);
        }
        $("#" + errorId).show().html(message);
        return true;
    },
    // Returns a string like "color and size" for any attributes w/ no
    // selected values
    missingAttributes: function() {
        var missing = [];
        var attrs = fl.Product.Inventory.allAttributes();
        var i = -1;
        var max = attrs.length;
        log.setup("product")("Looking for Missing Attributes in ", attrs);
        while (++i < max) {
            if (!attrs[i].value){
                missing[missing.length] = fl.Formatter.capitalizeString(attrs[i].key);
            }
        }
        if (!missing.length) {
            return null;
        }
        if (1 == missing.length) {
            return missing[0];
        }
        var s = fl.Product.Inventory.localeValue(missing[0]);
        i = 0/*=1-1*/; max = missing.length;
        while (++i < max) {
            if (i == max - 1) {
                s += Locale.conjunct;
            } else {
                s += ", ";
            }
            s += fl.Product.Inventory.localeValue(missing[i]);
        }
        return s;
    },
    // Localize text values for subsite language
    localeValue: function(val) {
        if ("Size" == val) {
            val = Locale.size;
        } else if ("Color" == val) {
            val = Locale.color;
        }
        return val;
    },
    // Called from sale/product with product inventory status object from the inventory service.
    // ignoreServer means the status variable is useless, but we should go ahead and update the page as if status were valid but didn't tell us anything interesting.
    updateProductPageWithInventoryStatus: function(productID, status, error, ignoreServer) {
        log.setup("product")("Checking Inventory");
        if(!status && !ignoreServer){
            log("Error checking inventory: ",error);
            return;
        }

        var serverSkusInStock = {};
        if (!ignoreServer && status.products && 0 < status.products.length) {
            var looks = status.products[0].looks;
            if (looks) {
                var i = looks.length;
                while (i--) {
                    var skus = looks[i].skus;
                    if (skus) {
                        var j = skus.length;
                        while (j--) {
                            var sku_id = skus[j].sku_id;
                            // Ignore data for skus that weren't registered at page load
                            if (fl.Product.Inventory.sku_data[sku_id]) {
                                if ("F" == skus[j].stat || "R" == skus[j].stat) { // server only tells us about skus in stock.
                                    serverSkusInStock[sku_id] = true;
                                }
                            }
                        }
                    }
                }
            }
        }

        // Only turn off skus if the server thinks they're out of stock -- otherwise defer to the CMS.
        var countInStock = 0;
        var waitList = null;
        if (gg && gg.WaitList) {
            waitList = gg.WaitList;
        }
        var max = fl.Product.Inventory.allSkus.length;
        i = -1;
        while (++i < max) { // TODO: might be able to go in reverse
            var sku = fl.Product.Inventory.allSkus[i];
            if (fl.Product.Inventory.sku_data[sku.id] && fl.Product.Inventory.sku_data[sku.id].in_stock) {
                if (!serverSkusInStock[sku.id] && !ignoreServer) {
                    fl.Product.Inventory.sku_data[sku.id].in_stock = false;
                }
                else {
                    ++countInStock;
                    waitList.setSkuInStock(sku.id); // tell the wait list to believe this sku is stock.  Do this from here so we're definitely in sync.
                }
            }
        }

        fl.Product.Inventory.selectValue('color', fl.Util.escapeSlashes(fl.Product.MetaImage.selectedColorId), 0);
        if (0 >= countInStock) {
            if ($('#wait_list_button_wrap') && $('#buy_now_button_wrap')) {
                $('#wait_list_button_wrap').show();
                $('#buy_now_button_wrap').hide();
            }
        }
        else if (countInStock < fl.Product.Inventory.allSkus.length) {
            $('#wait_list_function_link').show();
        } else {
            $('#wait_list_function_link').hide();
        }
    },
		// Called from /wl with product inventory status object from the inventory service.
    // ignoreServer means the status variable is useless, but we should go ahead and update the page as if status were valid but didn't tell us anything interesting.
    updateAvailableWaitListWithInventoryStatus: function(productID, status, error, ignoreServer) {
			log.setup("product")("Checking Wait List Item Status");
			
			$('#wait_list_items_available tr.loading').removeClass('loading');
			
			if (ignoreServer) { return; }
			else if(!status) {
        log("Error checking inventory: ",error);
        return;
      }

			var serverSkusInStock = fl.Product.Inventory.parseSkuStatusFromServer(status);
			
			for (var sku_id in serverSkusInStock) {
			  if (serverSkusInStock[sku_id] == 'R') { // item is reserved
			    $('#wait_list_items_available tr.sku-' + sku_id + " td.button_row").append('<p style="color:red; margin-top: 10px">CURRENTLY IN MEMBER\'S CARTS</p>');
			  }
			}
		},
		parseSkuStatusFromServer: function(status) {
		  var skus = {};
		  if (status && status.products && 0 < status.products.length) {
		    var looks = status.products[0].looks;
		    if (looks) {
          var i = looks.length;
          while (i--) {
            var lookSkus = looks[i].skus;
            if (lookSkus) {
              var j = lookSkus.length;
              while (j--) {
                var sku_id = lookSkus[j].sku_id;
                skus[sku_id] = lookSkus[j].stat;
              }
            }
          }
        }
		  }
		  return skus;
		},
    waitListEnabled: true,
    disableWaitList: function() {
        fl.Product.Inventory.waitListEnabled = false;
    }
};

var gg;
if (!gg.Sale) {
  gg.Sale = {};
}

gg.Sale.lookIDs = null;
gg.Sale.lookContainer = null;
gg.Sale.overlayDialog = null;

// Need to pass expected state so that missing a mouseover or mouseout event doesn't cause the state to become reversed
gg.Sale.tile_set_state = function(el, state) {
  if (!fl.Init.isInitialized()) {
    return;
  }

  el.find('div.title_bar, div.title_bar h2, div.title_bar h4')
    .removeClass("on")
    .iff("on" == state)
      .addClass("on");
};

gg.Sale.showWelcomeOverlay = function() {
  if (fl.Util.readCookie('welcome_overlay')) {
    fl.Util.expireCookie('welcome_overlay');

    gg.Sale.overlayDialog = fl.Util.getDialog("welcome_overlay", {
      dialogClass: 'welcome_overlay',
      position: ["center", 50],
      clickOverlay: false,
      overlayOpacity: "0.85",
      show: 'fade',
      hide: 'fade'
    });

    var contents_id = "welcome_overlay_gilt";

    if (identify_domain_name(document.location.host) == "fuse") {
      contents_id = "welcome_overlay_fuse";
    } else if (identify_domain_name(document.location.host) == "man" ) {
      contents_id = "welcome_overlay_man";
    } else {
      // Gilt
      if (gg.Usermeta.data().gender == 'm') {
        $('#' + contents_id).find("#welcome_container").addClass('gilt_man');
      }
    }

    gg.Sale.overlayDialog
      .html($('#' + contents_id).html())
      .dialog("open");
  }
};

gg.Sale.closeWelcomeOverlay = function() {
  gg.Sale.overlayDialog.dialog("close");
};

gg.Sale.addSoldOutOverlay = function(el, id) {
  el.addClass('filter_look_sold_out');

  if (gg.Sale.soldOutOverlayEl.length) {
    var as = el.find('a.product_image');
    if (as.length) {
      var os = as.find('span.sold_out');
      if (!os.length) {
        as.append($(gg.Sale.soldOutOverlayEl.clone(true)).show());
      }
    }
  }

  var vnb = $('#view_now_button_' + id);
  if (vnb.length && gg.Sale.waitListButtonEl.length) {
    vnb.css({backgroundImage: gg.Sale.waitListButtonEl.css("background-image")});
  }
};

gg.Sale.addReservedOverlay = function(el) {
  el.addClass('filter_look_reserved');

  if (gg.Sale.reservedOverlayEl.length) {
    var as = el.find('a.product_image');
    if (as.length) {
      var os = as.find('span.reserved');
      if (!os.length) {
        as.append($(gg.Sale.reservedOverlayEl.clone(true)).show());
      }
    }
  }
};

gg.Sale.updateSoldOutStatus = function(saleID, hideSoldOut, updateAvailableCount) {
  if (!gg.Sale.lookIDs) {
    gg.Sale.lookIDs = [];
    var products = $("#catalog .product[id^=product_]");
    var i = -1;
    var max = products.length;
    while (++i < max) {
      var match = products[i].id.match(gg.Sale.updateSoldOutStatus.test);
      if (match) {
        gg.Sale.lookIDs.push(match[1]);
      }
    }
  }
  if (1 > gg.Sale.lookIDs.length) {
    return;
  } else {
    var el = $('#product_' + gg.Sale.lookIDs[0]);
    if (!el.length) {
      return;
    }
    gg.Sale.lookContainer = el.parent();
    gg.Sale.soldOutOverlayEl = $('#look_sold_out_overlay_template');
    gg.Sale.waitListButtonEl = $('#wait_list_button_template');
    gg.Sale.viewNowButtonEl = $('#view_now_button_template');
    gg.Sale.reservedOverlayEl = $('#look_reserved_overlay_template');
  }

  var onSuccess = function(saleID, lookStatus) {
    if (hideSoldOut) {
      var ids = gg.Sale.lookIDs;
      var i = ids.length;
      while (i--) {
        var id = ids[i];
        if ("R" == lookStatus[id]) {
          el.show();
          gg.Sale.addReservedOverlay(el, id);
        } else if ("X" == lookStatus[id]) {
          $('#product_' + id).addClass('filter_look_sold_out').hide();
        } else {
          // do nothing -- defer to what was returned from rails.
          //$('#product_' + id).removeClass('filter_look_sold_out').show();
        }
      }
    } else {
      ids = gg.Sale.lookIDs;
      i = ids.length;
      while (i--) {
        id = ids[i];
        el = $('#product_' + id);
        if (el.length) {
          el.show();
          if ("R" == lookStatus[id]) {
            gg.Sale.addReservedOverlay(el, id);
          } else if ("X" == lookStatus[id]) {
            el.addClass('filter_look_sold_out');

            gg.Sale.addSoldOutOverlay(el, id);

            if (gg.Sale.waitListButtonEl) {
              $('#view_now_button_' + id).css({ backgroundImage: gg.Sale.waitListButtonEl.css("backgroundImage") });
            }
          } else {
            // do nothing -- defer to what was returned from rails.
            //el.removeClass('filter_look_sold_out');
            //el.find('img.sold_out').each(function(el) {
            //  el.remove();
            //});
            //var vnb = $('#view_now_button_' + id);
            //if (vnb && gg.Sale.viewNowButtonEl) {
            //  nb.style.backgroundImage = gg.Sale.viewNowButtonEl.style.backgroundImage;
            //}
          }
        }
      }
    }
    /*if (updateAvailableCount && gg_brand_product_hash) {
        var brandAvailableCount = {};
        for (id in lookStatus) {
            if ("F" == lookStatus[id]) {
                if (!brandAvailableCount[ gg_brand_product_hash[id] ]) {
                    brandAvailableCount[ gg_brand_product_hash[id] ] = 1;
                } else {
                    brandAvailableCount[ gg_brand_product_hash[id] ]++;
                }
            }
        }
        for (id in brandAvailableCount) {
            $("#brand_button_" + id + " h3").text(brandAvailableCount[id] + " Styles Left");
        }
        $(".brand_button h3:empty").text("No Styles Left");
    }*/
    if (gg.productFilter) {
      gg.productFilter.init(hideSoldOut);
    } else {
      gg.newProductFilter.hideSoldOutWithNullFilters = hideSoldOut;
      gg.newProductFilter.process();
    }
  };

  var onError = function() {
    if (gg.productFilter) {
      gg.productFilter.init(hideSoldOut);
    } else {
      gg.newProductFilter.hideSoldOutWithNullFilters = hideSoldOut;
    }
  };

  gg.Inventory.sale_status(saleID, onSuccess, onError);
};
gg.Sale.updateSoldOutStatus.test = /^product_(\d+)$/;

/*! SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/

var swfobject = function() {

	var UNDEF = "undefined",
		OBJECT = "object",
		SHOCKWAVE_FLASH = "Shockwave Flash",
		SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
		FLASH_MIME_TYPE = "application/x-shockwave-flash",
		EXPRESS_INSTALL_ID = "SWFObjectExprInst",

		win = window,
		doc = document,
		nav = navigator,

		domLoadFnArr = [],
		regObjArr = [],
		objIdArr = [],
		listenersArr = [],
		script,
		timer = null,
		storedAltContent = null,
		storedAltContentId = null,
		isDomLoaded = false,
		isExpressInstallActive = false;

	/* Centralized function for browser feature detection
		- Proprietary feature detection (conditional compiling) is used to detect Internet Explorer's features
		- User agent string detection is only used when no alternative is possible
		- Is executed directly for optimal performance
	*/
	var ua = function() {
		var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
			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+
				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] = /r/.test(d) ? parseInt(d.replace(/^.*r(.*)$/, "$1"), 10) : 0;
			}
		}
		else if (typeof win.ActiveXObject != UNDEF) {
			var a = null, fp6Crash = false;
			try {
				a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".7");
			}
			catch(e) {
				try {
					a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".6");
					playerVersion = [6,0,21];
					a.AllowScriptAccess = "always";	 // Introduced in fp6.0.47
				}
				catch(e) {
					if (playerVersion[0] == 6) {
						fp6Crash = true;
					}
				}
				if (!fp6Crash) {
					try {
						a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
					}
					catch(e) {}
				}
			}
			if (!fp6Crash && a) { // a will return null when ActiveX is disabled
				try {
					d = a.GetVariable("$version");	// Will crash fp6.0.21/23/29
					if (d) {
						d = d.split(" ")[1].split(",");
						playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
					}
				}
				catch(e) {}
			}
		}
		var u = nav.userAgent.toLowerCase(),
			p = nav.platform.toLowerCase(),
			webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
			ie = false,
			windows = p ? /win/.test(p) : /win/.test(u),
			mac = p ? /mac/.test(p) : /mac/.test(u);
		/*@cc_on ie = true; @if (@_win32) windows = true; @elif (@_mac) mac = true; @end @*/
		return { w3cdom:w3cdom, pv:playerVersion, webkit:webkit, ie:ie, win:windows, mac:mac };
	}();

	/* Cross-browser onDomLoad
		- Based on Dean Edwards' solution: http://dean.edwards.name/weblog/2006/06/again/
		- Will fire an event as soon as the DOM of a page is loaded (supported by Gecko based browsers - like Firefox -, IE, Opera9+, Safari)
	*/
	var onDomLoad = function() {
		if (!ua.w3cdom) {
			return;
		}
		addDomLoadEvent(main);
		if (ua.ie && ua.win) {
			try {	 // Avoid a possible Operation Aborted error
				doc.write("<scr" + "ipt id=__ie_ondomload defer=true src=//:></scr" + "ipt>"); // String is split into pieces to avoid Norton AV to add code that can cause errors
				script = getElementById("__ie_ondomload");
				if (script) {
					addListener(script, "onreadystatechange", checkReadyState);
				}
			}
			catch(e) {}
		}
		if (ua.webkit && typeof doc.readyState != UNDEF) {
			timer = setInterval(function() { if (/loaded|complete/.test(doc.readyState)) { callDomLoadFunctions(); }}, 10);
		}
		if (typeof doc.addEventListener != UNDEF) {
			doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, null);
		}
		addLoadEvent(callDomLoadFunctions);
	}();

	function checkReadyState() {
		if (script.readyState == "complete") {
			script.parentNode.removeChild(script);
			callDomLoadFunctions();
		}
	}

	function callDomLoadFunctions() {
		if (isDomLoaded) {
			return;
		}
		if (ua.ie && ua.win) { // Test if we can really add elements to the DOM; we don't want to fire it too early
			var s = createElement("span");
			try { // Avoid a possible Operation Aborted error
				var t = doc.getElementsByTagName("body")[0].appendChild(s);
				t.parentNode.removeChild(t);
			}
			catch (e) {
				return;
			}
		}
		isDomLoaded = true;
		if (timer) {
			clearInterval(timer);
			timer = null;
		}
		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+
		}
	}

	/* Cross-browser onload
		- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
		- Will fire an event as soon as a web page including all of its assets are loaded
	 */
	function addLoadEvent(fn) {
		if (typeof win.addEventListener != UNDEF) {
			win.addEventListener("load", fn, false);
		}
		else if (typeof doc.addEventListener != UNDEF) {
			doc.addEventListener("load", fn, false);
		}
		else if (typeof win.attachEvent != UNDEF) {
			addListener(win, "onload", fn);
		}
		else if (typeof win.onload == "function") {
			var fnOld = win.onload;
			win.onload = function() {
				fnOld();
				fn();
			};
		}
		else {
			win.onload = fn;
		}
	}

	/* Main function
		- Will preferably execute onDomLoad, otherwise onload (as a fallback)
	*/
	function main() { // Static publishing only
		var rl = regObjArr.length;
		for (var i = 0; i < rl; i++) { // For each registered object element
			var id = regObjArr[i].id;
			if (ua.pv[0] > 0) {
				var obj = getElementById(id);
				if (obj) {
					regObjArr[i].width = obj.getAttribute("width") ? obj.getAttribute("width") : "0";
					regObjArr[i].height = obj.getAttribute("height") ? obj.getAttribute("height") : "0";
					if (hasPlayerVersion(regObjArr[i].swfVersion)) { // Flash plug-in version >= Flash content version: Houston, we have a match!
						if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements
							fixParams(obj);
						}
						setVisibility(id, true);
					}
					else if (regObjArr[i].expressInstall && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) { // Show the Adobe Express Install dialog if set by the web page author and if supported (fp6.0.65+ on Win/Mac OS only)
						showExpressInstall(regObjArr[i]);
					}
					else { // Flash plug-in and Flash content version mismatch: display alternative content instead of Flash content
						displayAltContent(obj);
					}
				}
			}
			else {	// If no fp is installed, we let the object element do its job (show alternative content)
				setVisibility(id, true);
			}
		}
	}

	/* Fix nested param elements, which are ignored by older webkit engines
		- This includes Safari up to and including version 1.2.2 on Mac OS 10.3
		- Fall back to the proprietary embed element
	*/
	function fixParams(obj) {
		var nestedObj = obj.getElementsByTagName(OBJECT)[0];
		if (nestedObj) {
			var e = createElement("embed"), a = nestedObj.attributes;
			if (a) {
				var al = a.length;
				for (var i = 0; i < al; i++) {
					if (a[i].nodeName == "DATA") {
						e.setAttribute("src", a[i].nodeValue);
					}
					else {
						e.setAttribute(a[i].nodeName, a[i].nodeValue);
					}
				}
			}
			var c = nestedObj.childNodes;
			if (c) {
				var cl = c.length;
				for (var j = 0; j < cl; j++) {
					if (c[j].nodeType == 1 && c[j].nodeName == "PARAM") {
						e.setAttribute(c[j].getAttribute("name"), c[j].getAttribute("value"));
					}
				}
			}
			obj.parentNode.replaceChild(e, obj);
		}
	}

	/* Show the Adobe Express Install dialog
		- Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
	*/
	function showExpressInstall(regObj) {
		isExpressInstallActive = true;
		var obj = getElementById(regObj.id);
		if (obj) {
			if (regObj.altContentId) {
				var ac = getElementById(regObj.altContentId);
				if (ac) {
					storedAltContent = ac;
					storedAltContentId = regObj.altContentId;
				}
			}
			else {
				storedAltContent = abstractAltContent(obj);
			}
			if (!(/%$/.test(regObj.width)) && parseInt(regObj.width, 10) < 310) {
				regObj.width = "310";
			}
			if (!(/%$/.test(regObj.height)) && parseInt(regObj.height, 10) < 137) {
				regObj.height = "137";
			}
			doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
			var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
				dt = doc.title,
				fv = "MMredirectURL=" + win.location + "&MMplayerType=" + pt + "&MMdoctitle=" + dt,
				replaceId = regObj.id;
			// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
			// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
			if (ua.ie && ua.win && obj.readyState != 4) {
				var newObj = createElement("div");
				replaceId += "SWFObjectNew";
				newObj.setAttribute("id", replaceId);
				obj.parentNode.insertBefore(newObj, obj); // Insert placeholder div that will be replaced by the object element that loads expressinstall.swf
				obj.style.display = "none";
				var fn = function() {
					obj.parentNode.removeChild(obj);
				};
				addListener(win, "onload", fn);
			}
			createSWF({ data:regObj.expressInstall, id:EXPRESS_INSTALL_ID, width:regObj.width, height:regObj.height }, { flashvars:fv }, replaceId);
		}
	}

	/* Functions to abstract and display alternative content
	*/
	function displayAltContent(obj) {
		if (ua.ie && ua.win && obj.readyState != 4) {
			// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
			// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
			var el = createElement("div");
			obj.parentNode.insertBefore(el, obj); // Insert placeholder div that will be replaced by the alternative content
			el.parentNode.replaceChild(abstractAltContent(obj), el);
			obj.style.display = "none";
			var fn = function() {
				obj.parentNode.removeChild(obj);
			};
			addListener(win, "onload", fn);
		}
		else {
			obj.parentNode.replaceChild(abstractAltContent(obj), obj);
		}
	}

	function abstractAltContent(obj) {
		var ac = createElement("div");
		if (ua.win && ua.ie) {
			ac.innerHTML = obj.innerHTML;
		}
		else {
			var nestedObj = obj.getElementsByTagName(OBJECT)[0];
			if (nestedObj) {
				var c = nestedObj.childNodes;
				if (c) {
					var cl = c.length;
					for (var i = 0; i < cl; i++) {
						if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
							ac.appendChild(c[i].cloneNode(true));
						}
					}
				}
			}
		}
		return ac;
	}

	/* Cross-browser dynamic SWF creation
	*/
	function createSWF(attObj, parObj, id) {
		var r, el = getElementById(id);
		if (el) {
			if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
				attObj.id = id;
			}
			if (ua.ie && ua.win) { // IE, the object element and W3C DOM methods do not combine: fall back to outerHTML
				var att = "";
				for (var i in attObj) {
					if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries, like Object.prototype.toJSONString = function() {}
						if (i.toLowerCase() == "data") {
							parObj.movie = attObj[i];
						}
						else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							att += ' class="' + attObj[i] + '"';
						}
						else if (i.toLowerCase() != "classid") {
							att += ' ' + i + '="' + attObj[i] + '"';
						}
					}
				}
				var par = "";
				for (var j in parObj) {
					if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
						par += '<param name="' + j + '" value="' + parObj[j] + '" />';
					}
				}
				el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
				objIdArr[objIdArr.length] = attObj.id; // Stored to fix object 'leaks' on unload (dynamic publishing only)
				r = getElementById(attObj.id);
			}
			else if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements: fall back to the proprietary embed element
				var e = createElement("embed");
				e.setAttribute("type", FLASH_MIME_TYPE);
				for (var k in attObj) {
					if (attObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
						if (k.toLowerCase() == "data") {
							e.setAttribute("src", attObj[k]);
						}
						else if (k.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							e.setAttribute("class", attObj[k]);
						}
						else if (k.toLowerCase() != "classid") { // Filter out IE specific attribute
							e.setAttribute(k, attObj[k]);
						}
					}
				}
				for (var l in parObj) {
					if (parObj[l] != Object.prototype[l]) { // Filter out prototype additions from other potential libraries
						if (l.toLowerCase() != "movie") { // Filter out IE specific param element
							e.setAttribute(l, parObj[l]);
						}
					}
				}
				el.parentNode.replaceChild(e, el);
				r = e;
			}
			else { // Well-behaving browsers
				var o = createElement(OBJECT);
				o.setAttribute("type", FLASH_MIME_TYPE);
				for (var m in attObj) {
					if (attObj[m] != Object.prototype[m]) { // Filter out prototype additions from other potential libraries
						if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							o.setAttribute("class", attObj[m]);
						}
						else if (m.toLowerCase() != "classid") { // Filter out IE specific attribute
							o.setAttribute(m, attObj[m]);
						}
					}
				}
				for (var n in parObj) {
					if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // Filter out prototype additions from other potential libraries and IE specific param element
						createObjParam(o, n, parObj[n]);
					}
				}
				el.parentNode.replaceChild(o, el);
				r = o;
			}
		}
		return r;
	}

	function createObjParam(el, pName, pValue) {
		var p = createElement("param");
		p.setAttribute("name", pName);
		p.setAttribute("value", pValue);
		el.appendChild(p);
	}

	/* Cross-browser SWF removal
		- Especially needed to safely and completely remove a SWF in Internet Explorer
	*/
	function removeSWF(id) {
		var obj = getElementById(id);
		if (obj && (obj.nodeName == "OBJECT" || obj.nodeName == "EMBED")) {
			if (ua.ie && ua.win) {
				if (obj.readyState == 4) {
					removeObjectInIE(id);
				}
				else {
					win.attachEvent("onload", function() {
						removeObjectInIE(id);
					});
				}
			}
			else {
				obj.parentNode.removeChild(obj);
			}
		}
	}

	function removeObjectInIE(id) {
		var obj = getElementById(id);
		if (obj) {
			for (var i in obj) {
				if (typeof obj[i] == "function") {
					obj[i] = null;
				}
			}
			obj.parentNode.removeChild(obj);
		}
	}

	/* Functions to optimize JavaScript compression
	*/
	function getElementById(id) {
		var el = null;
		try {
			el = doc.getElementById(id);
		}
		catch (e) {}
		return el;
	}

	function createElement(el) {
		return doc.createElement(el);
	}

	/* Updated attachEvent function for Internet Explorer
		- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
	*/
	function addListener(target, eventType, fn) {
		target.attachEvent(eventType, fn);
		listenersArr[listenersArr.length] = [target, eventType, fn];
	}

	/* 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;
	}

	/* Cross-browser dynamic CSS creation
		- Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
	*/
	function createCSS(sel, decl) {
		if (ua.ie && ua.mac) {
			return;
		}
		var h = doc.getElementsByTagName("head")[0], s = createElement("style");
		s.setAttribute("type", "text/css");
		s.setAttribute("media", "screen");
		if (!(ua.ie && ua.win) && typeof doc.createTextNode != UNDEF) {
			s.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
		}
		h.appendChild(s);
		if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
			var ls = doc.styleSheets[doc.styleSheets.length - 1];
			if (typeof ls.addRule == OBJECT) {
				ls.addRule(sel, decl);
			}
		}
	}

	function setVisibility(id, isVisible) {
		var v = isVisible ? "visible" : "hidden";
		if (isDomLoaded && getElementById(id)) {
			getElementById(id).style.visibility = v;
		}
		else {
			createCSS("#" + id, "visibility:" + v);
		}
	}

	/* Filter to avoid XSS attacks
	*/
	function urlEncodeIfNecessary(s) {
		var regex = /[\\\"<>\.;]/;
		var hasBadChars = regex.exec(s) != null;
		return hasBadChars ? encodeURIComponent(s) : s;
	}

	/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
	*/
	var cleanup = function() {
		if (ua.ie && ua.win) {
			window.attachEvent("onunload", function() {
				// remove listeners to avoid memory leaks
				var ll = listenersArr.length;
				for (var i = 0; i < ll; i++) {
					listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
				}
				// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
				var il = objIdArr.length;
				for (var j = 0; j < il; j++) {
					removeSWF(objIdArr[j]);
				}
				// cleanup library's main closures to avoid memory leaks
				for (var k in ua) {
					ua[k] = null;
				}
				ua = null;
				for (var l in swfobject) {
					swfobject[l] = null;
				}
				swfobject = null;
			});
		}
	}();


	return {
		/* Public API
			- Reference: http://code.google.com/p/swfobject/wiki/SWFObject_2_0_documentation
		*/
		registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr) {
			if (!ua.w3cdom || !objectIdStr || !swfVersionStr) {
				return;
			}
			var regObj = {};
			regObj.id = objectIdStr;
			regObj.swfVersion = swfVersionStr;
			regObj.expressInstall = xiSwfUrlStr ? xiSwfUrlStr : false;
			regObjArr[regObjArr.length] = regObj;
			setVisibility(objectIdStr, false);
		},

		getObjectById: function(objectIdStr) {
			var r = null;
			if (ua.w3cdom) {
				var o = getElementById(objectIdStr);
				if (o) {
					var n = o.getElementsByTagName(OBJECT)[0];
					if (!n || (n && typeof o.SetVariable != UNDEF)) {
							r = o;
					}
					else if (typeof n.SetVariable != UNDEF) {
						r = n;
					}
				}
			}
			return r;
		},

		embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj) {
			if (!ua.w3cdom || !swfUrlStr || !replaceElemIdStr || !widthStr || !heightStr || !swfVersionStr) {
				return;
			}
			widthStr += ""; // Auto-convert to string
			heightStr += "";
			if (hasPlayerVersion(swfVersionStr)) {
				setVisibility(replaceElemIdStr, false);
				var att = {};
				if (attObj && typeof attObj === OBJECT) {
					for (var i in attObj) {
						if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries
							att[i] = attObj[i];
						}
					}
				}
				att.data = swfUrlStr;
				att.width = widthStr;
				att.height = heightStr;
				var par = {};
				if (parObj && typeof parObj === OBJECT) {
					for (var j in parObj) {
						if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
							par[j] = parObj[j];
						}
					}
				}
				if (flashvarsObj && typeof flashvarsObj === OBJECT) {
					for (var k in flashvarsObj) {
						if (flashvarsObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
							if (typeof par.flashvars != UNDEF) {
								par.flashvars += "&" + k + "=" + flashvarsObj[k];
							}
							else {
								par.flashvars = k + "=" + flashvarsObj[k];
							}
						}
					}
				}
				addDomLoadEvent(function() {
					createSWF(att, par, replaceElemIdStr);
					if (att.id == replaceElemIdStr) {
						setVisibility(replaceElemIdStr, true);
					}
				});
			}
			else if (xiSwfUrlStr && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) {
				isExpressInstallActive = true; // deferred execution
				setVisibility(replaceElemIdStr, false);
				addDomLoadEvent(function() {
					var regObj = {};
					regObj.id = regObj.altContentId = replaceElemIdStr;
					regObj.width = widthStr;
					regObj.height = heightStr;
					regObj.expressInstall = xiSwfUrlStr;
					showExpressInstall(regObj);
				});
			}
		},

		getFlashPlayerVersion: function() {
			return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
		},

		hasFlashPlayerVersion: hasPlayerVersion,

		createSWF: function(attObj, parObj, replaceElemIdStr) {
			if (ua.w3cdom) {
				return createSWF(attObj, parObj, replaceElemIdStr);
			}
			else {
				return undefined;
			}
		},

		removeSWF: function(objElemIdStr) {
			if (ua.w3cdom) {
				removeSWF(objElemIdStr);
			}
		},

		createCSS: function(sel, decl) {
			if (ua.w3cdom) {
				createCSS(sel, decl);
			}
		},

		addDomLoadEvent: addDomLoadEvent,

		addLoadEvent: addLoadEvent,

		getQueryParamValue: function(param) {
			var q = doc.location.search || doc.location.hash;
			if (param == null) {
				return urlEncodeIfNecessary(q);
			}
			if (q) {
				var pairs = q.substring(1).split("&");
				for (var i = 0; i < pairs.length; i++) {
					if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
						return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
					}
				}
			}
			return "";
		},

		// For internal usage only
		expressInstallCallback: function() {
			if (isExpressInstallActive && storedAltContent) {
				var obj = getElementById(EXPRESS_INSTALL_ID);
				if (obj) {
					obj.parentNode.replaceChild(storedAltContent, obj);
					if (storedAltContentId) {
						setVisibility(storedAltContentId, true);
						if (ua.ie && ua.win) {
							storedAltContent.style.display = "block";
						}
					}
					storedAltContent = null;
					storedAltContentId = null;
					isExpressInstallActive = false;
				}
			}
		}
	};
}();

var gg;
if (!gg) {
    gg = {};
}

gg.WaitList = {
    formText: '',
    omnitureAction: function() {},
    skuData: [],
    skusInStock: {},
    attrSkus: [],
    colors: [],
    colorsSizes: {},
    skuColors: [],
    skuSizes: [],
    sizeOrdering: {},
    defaultReason: '',
    colorLooks: {},
    registerSku: function(color_id, size_id, sku_id, look_id) {
        gg.WaitList.skuData.push({
            color: color_id,
            size: size_id,
            id: sku_id,
            lookId: look_id
        });
    },
    includeSku: function (color, size, sku_id, look_id) {
        var attrTag = '';

        if (!color) {
            color = '';
        }
        attrTag = attrTag + color;
        gg.WaitList.colors.push(color);
        gg.WaitList.skuColors[sku_id] = color;
        gg.WaitList.colorLooks[color] = look_id;
        if (!gg.WaitList.colorsSizes[color]) {
            gg.WaitList.colorsSizes[color] = [];
        }
        if (size) {
            gg.WaitList.colorsSizes[color].push(size); 
        }

        attrTag = attrTag + '_';

        if (size) {
            gg.WaitList.colorsSizes[color].push(size);
            attrTag = attrTag + size;
            gg.WaitList.skuSizes[sku_id] = size;
        }

        gg.WaitList.attrSkus[attrTag] = sku_id;
    },
    injectSkuId: function() {
        var color = $('#wl_colors').val() || '';
        var size = $('#wl_sizes').val() || '';
        $('#wl_sku_id_input').val(gg.WaitList.attrSkus[ color + '_' + size ]);
    },
    populateColors: function(selected_color) {
        var cdd = $('#wl_colors').empty();

        var colors = gg.WaitList.colors;
        var i = -1;
        var max = colors.length;
        while (++i < max) {
            var color = colors[i];
            cdd.append("<option value='" + color + "'>" + color + "</option>");
            if (color == selected_color) {
                cdd.val(selected_color);
            }
        }

        gg.WaitList.injectSkuId();
    },
    populateSizes: function(color, selected_size) {
        var sdd = $('#wl_sizes').empty();

        var sizes = gg.WaitList.colorsSizes[color];
        if (sizes) {
            var i = -1;
            var max = sizes.length;
            while (++i < max) {
                var size = sizes[i];
                sdd.append("<option value='" + size + "'>" + size + "</option>");
                if (size == selected_size) {
                    sdd.val(selected_size);
                }
            }
        }

        var looks = gg.WaitList.colorLooks;
        for (var c in looks) {
            if (looks.hasOwnProperty(c)) {
                var element_id = 'wl_look_' + looks[c];
                var el = $("#" + element_id);
                if (el.length) {
                    if (c == color) {
                        el.show();
                    } else {
                        el.hide();
                    }
                }
            }
        }

        gg.WaitList.injectSkuId();
    },
    initializeForm: function(wait_list_reason, sku_id, sequence, order_id, suppress_omniture) {
        $("#dialog_cart").dialog("close");
        var d = fl.Util.getDialog("dialog_waitlist", {
          title: Locale.your_wait_list,
          width: 673
        }).dialog("open");

        d.html(gg.WaitList.formText);
        $('#wait_list_reason').html(wait_list_reason || gg.WaitList.defaultReason);

        var user_id = fl.Util.readHashedCookie('user_id');
        if (user_id) {
            $('#wl_user_id').val(user_id);
        }

        if (order_id) {
            $('#wl_order_id').val(order_id);
        }

        gg.WaitList.attrSkus.length = 0;
        gg.WaitList.colors.length = 0;
        gg.WaitList.colorsSizes = {};
        gg.WaitList.skuColors.length = 0;
        gg.WaitList.skuSizes.length = 0;

        var skus = gg.WaitList.skuData;
        var i = -1, max = skus.length;
        while (++i < max) {
            var s = skus[i];
            if (!gg.WaitList.skusInStock[s.id] || s.id == sku_id) {
                gg.WaitList.includeSku(s.color, s.size, s.id, s.lookId);
            }
        }

        gg.WaitList.colors = $.uniq(gg.WaitList.colors).sort();

        var sortFunc = function(a, b) {
            if (gg.WaitList.sizeOrdering[a] && gg.WaitList.sizeOrdering[b]) {
                if (gg.WaitList.sizeOrdering[a] < gg.WaitList.sizeOrdering[b]) {
                    return -1;
                } else if (gg.WaitList.sizeOrdering[a] > gg.WaitList.sizeOrdering[b]) {
                    return 1;
                } else {
                    return 0;
                }
            } else {
                if (a.length < b.length) {
                    return -1;
                } else if (a.length > b.length) {
                    return 1;
                } else if (a < b) {
                    return -1;
                } else if (a > b) {
                    return 1;
                } else {
                    return 0;
                }
            }
        };
        var sizes = gg.WaitList.colorsSizes;
        for (var c in sizes) {
            if (sizes.hasOwnProperty(c)) {
                sizes[c] = $.uniq(sizes[c]).sort(sortFunc);
            }
        }

        gg.WaitList.populateColors(gg.WaitList.skuColors[sku_id] || fl.Product.MetaImage.selectedColorId);

        if (0 < gg.WaitList.colors.length) {
            $('#wl_color_header').html(Locale.color);
            $('#wl_colors').show(); // TODO: might need to be .css({ display: 'inline' });
        }

        gg.WaitList.populateSizes($('#wl_colors').val(), gg.WaitList.skuSizes[sku_id]); // TODO: What's up with wl_colors?  it doesn't seem to exist

        if (0 < gg.WaitList.skuSizes.length) {
            $('#wl_size_header').html(Locale.size);
            $('#wl_sizes').show();
        }

        if ("return" == sequence) { // TODO: might need to be .css({ display: 'inline' });
            $('#wl_return_link').show();
        } else {
            $('#wl_continue_link').show();
        }

        if (!suppress_omniture) {
            fl.Omniture.track("wait_list", "wait list: select item to add");
        }
    },
    popupForm: function(wait_list_reason, sku_id, sequence, order_id) {
        gg.WaitList.initializeForm(wait_list_reason, sku_id, sequence, order_id);
    },
    processForm: function() {
        var sku_id;
        var el = $('#wl_sku_id_input');
        if (el) {
            sku_id = el.val();
        }
        $.ajax({
            url: '/bb/wait_list',
            type: 'GET',
            data: $('#wl_form').serialize(),
            error: function(){
                $('#wait_list_reason').html(Locale.wait_list_unavailable);
                $('#wait_list').html('');
            },
            success: function() {
                if (sku_id) {
                    fl.Omniture.track('wait_list', 'wait list: add to wait list', { products: [ ";" +  sku_id ], events: [ 'event9' ] } );
                }
                $('#wait_list_reason').html(Locale.wait_list_success($("table.cart .thumbnail + td").html().split(/<[Bb][Rr]>/)[1])); // NOTE: assumes there is always a 2nd line
                $('#wait_list').html('');
                //$("#dialog_waitlist").dialog("close");
                //$("select").show();
            }
        });
    },
    updateStockData: function(productID, status, error) {
        // app/views/default/wait_list/new.erb.  This is used there; on the product page, we use setSkuInStock, below.
        if (!status) {
            return;
        }
        gg.WaitList.skusInStock = {};
        var countInStock = 0;
        if (status['products'] && status['products'].length > 0) {
            var looks = status['products'][0]['looks'];
            if (looks) {
                for (var i = 0, n = looks.length; i < n; ++i) {
                    var skus = looks[i]['skus'];
                    if (skus) {
                        for (var j = 0, nn = skus.length; j < nn; ++j) {
                            if (skus[j]['stat'] == 'F' ) {
                                gg.WaitList.skusInStock[skus[j]['sku_id']] = true;
                            }
                        }
                    }
                }
            }
        }
    },
    setSkuInStock: function(skuID) {
        // See product.js -- we want to have the exact same view of what's in stock as the product JS has.
        gg.WaitList.skusInStock[skuID] = true;
    }
};


// Interface to gilt's track log processor. This lets us record
// events that occur client side in server side logs for asynchronous processing

var gg;
if (!gg) {
    gg = {};
}

gg.TrackLog = {
  // Ex: gg.TrackLog.record('add_to_cart', {sku_id: 123299, sale_id: 2342341, st: 0});
  record: function(event_name, params) {
    params.key = event_name;
    jQuery.get('/track', gg.TrackLog.encodeEvents(params));
  },
  encodeEvents: function(params) {
    var final_params = 'tlp=';
    var query_params = encodeURIComponent(jQuery.param(params));
    final_params += encodeURIComponent('1=' + query_params);
    return final_params;
  }
};



var gg;
if (!gg) {
    gg = {};
}

//New Architecture
gg.newProductFilter = {
    key: '',
    filterTypes: {
        category: {
            sortedKeys: [],
            values: {},
            displayPrefix: ["Category", "Categories"],
            allDisplay: "by Category"
        },
        size: {
            sortedKeys: [],
            values: {},
            displayPrefix: ["Size", "Sizes"],
            allDisplay: "by Size"
        }
    },
    filterables: ".product, .brand_button:not(.selected), .drop_down_content a, .sale_block",
    hideables: ".product, .brand_button, .sale_block",
    selectables: ".drop_down_content a",
    hideSoldOutWithNullFilters: false,
    isScrolling: false,
    allowMultipleFilters: false,
    useAllDisplay: false,
    currentState: {},
    defaultState: {}
};
gg.newProductFilter.process = function() {
    var isEmpty = true;
    for (var t in gg.newProductFilter.currentState) {
        var emptyType = true;
        if (gg.newProductFilter.currentState.hasOwnProperty(t) && gg.newProductFilter.filterTypes.hasOwnProperty(t)) {
            var k = gg.newProductFilter.currentState[t].length;
            if (k) {
                while (k--) {
                    if (gg.newProductFilter.filterTypes[t].values.hasOwnProperty(gg.newProductFilter.currentState[t][k])) {
                        isEmpty = false;
                        emptyType = false;
                        break;
                    }
                }
            }
        }
        if (emptyType) {
            delete gg.newProductFilter.currentState[t];
        }
    }
    if (!isEmpty) {
        var toShow = $(gg.newProductFilter.hideables);
        var toShow2 = $(gg.newProductFilter.selectables);
        var toSelect = $("empty");
        var toSoftSelect = $("empty");

        for (var type in gg.newProductFilter.currentState) {
            var orFilter = $("empty");
            var orFilter2 = $("empty");
            var i = gg.newProductFilter.currentState[type].length;
            if (i) {
                while (i--) {
                    var v = gg.newProductFilter.filterTypes[type].values[gg.newProductFilter.currentState[type][i]];
                    if (v) {
                        var a = v.alias;
                        var j = a.length;
                        if (j) {
                            while (j--) {
                                orFilter = orFilter.add($(gg.newProductFilter.hideables).filter("." + a[j].replace(".", "\\.")));
                                toSoftSelect = toSoftSelect.add("#" + a[j]);
                            }
                        }

                        orFilter = orFilter.add($(gg.newProductFilter.hideables).filter("." + gg.newProductFilter.currentState[type][i].replace(".", "\\.")));
                        orFilter2 = orFilter2.add($("#" + gg.newProductFilter.currentState[type][i].replace(".", "\\.")).parent().children());
                        orFilter2 = orFilter2.add($(gg.newProductFilter.selectables).not($("#" + gg.newProductFilter.currentState[type][i].replace(".", "\\.")).parent().children()).filter("." + gg.newProductFilter.currentState[type][i].replace(".", "\\.")));
                        toSelect = toSelect.add("#" + gg.newProductFilter.currentState[type][i].replace(".", "\\."));
                    }
                }
            } else {
                var all = gg.newProductFilter.filterTypes[type].displayContainer.find(".drop_down_content a:first");
                a = gg.newProductFilter.filterTypes[type].values[all.id()].alias;
                j = a.length;
                if (j) {
                    while (j--) {
                        orFilter = orFilter.add($(gg.newProductFilter.hideables).filter("." + a[j].replace(".", "\\.")));
                        toSoftSelect = toSoftSelect.add("#" + a[j]);
                    }
                }
                toSelect = toSelect.add(all);
            }
            toShow = toShow.not(toShow.not(orFilter)); // looks wierd, but it works
            toShow2 = toShow2.not(toShow2.not(orFilter2));
        }

        $(gg.newProductFilter.hideables).not(toShow).hide();
        $(gg.newProductFilter.selectables).not(toShow2).hide();
        $(gg.newProductFilter.selectables).not(toSelect).removeClass("selected");
        $(gg.newProductFilter.selectables).not(toSoftSelect).removeClass("soft");

        toShow.show();
        toShow2.show();
        toSelect.addClass("selected");
        toSoftSelect.addClass("soft");
    } else {
        $(gg.newProductFilter.filterables).show().removeClass("selected").removeClass("soft");
        $(gg.newProductFilter.hideables).filter(".selected").show().removeClass("soft");
        $(".drop_down_content").find("a:first").addClass("selected");
        if (gg.newProductFilter.hideSoldOutWithNullFilters) {
            $(gg.newProductFilter.hideables).filter(".filter_look_sold_out").hide();
            $(gg.newProductFilter.hideables).not(".filter_look_sold_out").show();
        }
    }

    gg.newProductFilter.display();

    gg.newProductFilter.store();

    gg.newProductFilter.toggleStuff();

    $(document).trigger("catalogchanged");
};
gg.newProductFilter.toggleStuff = function() {
    /*for (type in gg.newProductFilter.filterTypes) { // If a filter is empty (or only has 1 option other than 'All'), hide it
        if (!gg.newProductFilter.filterTypes[type].displayContainer.find(".drop_down_content a").not(":first").filter(".selected").length &&
            $.grep(gg.newProductFilter.filterTypes[type].displayContainer.find(".drop_down_content a"), function(a) {
            return $(a).css("display") != "none";
        }).length < 3) {
            gg.newProductFilter.filterTypes[type].displayContainer.hide();
        } else {
            gg.newProductFilter.filterTypes[type].displayContainer.show();
        }
    }*/

    if (!$("#catalog .product:visible").length) { // Show a message if everything in the current filter is sold out
        $("#all_sold_out").show();
    } else {
        $("#all_sold_out").hide();
    }

    if ($("#catalog .product:visible").length >= parseInt($("#back_to_top").attr("reqlooks"))) { // Hide the back to top link if too few products are visible
        $("#back_to_top").show();
    } else {
        $("#back_to_top").hide();
    }

    //if ($(".brand_button:visible").length && !$(".brand_button.selected:visible").length) { // current tab got hidden, select the first visible one
        //$("a.brand_button:visible:first").click();
    //}
};
gg.newProductFilter.display = function() { // Should they be in alphabetical order, or the order they were added?
    for(var type in gg.newProductFilter.filterTypes) {
        var text;
        if (gg.newProductFilter.currentState[type] && gg.newProductFilter.currentState[type].length) {
            var i = -1;
            var max = gg.newProductFilter.currentState[type].length;
            text = gg.newProductFilter.filterTypes[type].displayPrefix[ (max > 1) ? 1 : 0 ] + ": ";
            while (++i < max) {
                text += gg.newProductFilter.filterTypes[type].values[ gg.newProductFilter.currentState[type][i] ].name;
                if (i < max - 1) {
                    text += ", ";
                }
            }
            if (text.length > 32) {
                text = text.substr(0, 30) + "...";
            }
        } else {
            text = gg.newProductFilter.filterTypes[type].displayElement.text();
            if (text.indexOf(":") != -1) {
                if (gg.newProductFilter.useAllDisplay) {
                    text = gg.newProductFilter.filterTypes[type].allDisplay;
                } else {
                    text = gg.newProductFilter.filterTypes[type].displayPrefix[ gg.newProductFilter.allowMultipleFilters ? 1 : 0 ] + ": " + Locale.all;
                }
            }
        }
        gg.newProductFilter.filterTypes[type].displayElement.text(text);
    }
};
gg.newProductFilter.populate = function() {
    for (var type in gg.newProductFilter.filterTypes) {
        var filter = gg.newProductFilter.filterTypes[type];
        var content = $(filter.displayContainer).find(".drop_down_content");
        var index = -1;
        var maxValues = filter.sortedKeys.length;
        while (++index < maxValues) {
            (function() {
                var t = type;
                var v = filter.values[filter.sortedKeys[index]];
                if (!v) {
                    return;
                }
                var el = $($.format("<a id=\"{0}\" class=\"{2}\" href=\"#\">{1}</a>", filter.sortedKeys[index], v.name, v.depends.join(" ")));
                el.click(function(ev) {
                    var el = $(this);
                    el.parent().parent().parent().hide();
                    if (!gg.newProductFilter.currentState[t]) {
                        gg.newProductFilter.currentState[t] = [];
                    }
                    if (!el.hasClass("selected")) {
                        if (el.prevAll().length) {
                            gg.newProductFilter.currentState[t].push(el.id());
                        }
                        if (!gg.newProductFilter.allowMultipleFilters) { // not tested
                            el.siblings(".selected").each(function(_, sib) {
                                index = $.inArray($(sib).id(), gg.newProductFilter.currentState[t]);
                                if (index != -1) {
                                    gg.newProductFilter.currentState[t].splice(index, 1);
                                }
                            });
                        }
                        var a = gg.newProductFilter.filterTypes[t].values[el.id()].alias;
                        var i = a.length;
                        if (i) {
                            while (i--) {
                                var index = $.inArray(a[i], gg.newProductFilter.currentState[t]);
                                if (index != -1) {
                                    gg.newProductFilter.currentState[t].splice(index, 1);
                                }
                            }
                        }
                    } else {
                        index = $.inArray(el.id(), gg.newProductFilter.currentState[t]);
                        if (index != -1) {
                            gg.newProductFilter.currentState[t].splice(index, 1);
                        }
                    }

                    gg.newProductFilter.process();
                    gg.newProductFilter.track(t);
                    ev.preventDefault();
                });
                content.append(el);
            })();
        }
    }
};
gg.newProductFilter.init = function() {
    gg.productFilter = false;
    var otherMenus = $("empty");
    var delay;
    for (var t in gg.newProductFilter.filterTypes) {
        (function() {
            var type = t;
            var windowClickHandler = function(event) {
                if (!$(event.target).closest(".menu").length) {
                    f("hide");
                }
            };
            var filter = gg.newProductFilter.filterTypes[type];
            filter.displayContainer = $("#" + type + "_scroll_container");
            filter.displayElement = $("#" + type + "_filter_header");
            otherMenus = otherMenus.add("#" + type + "_content");
            var f = function(mode, ev) {
                clearTimeout(delay);
                if ((mode == "show" || mode == "toggle") && $("#" + type + "_content:hidden").length) {
                    filter.displayElement.addClass("active");
                    $("#" + type + "_content").show();
                    otherMenus.not("#" + type + "_content").hide();
                    gg.newProductFilter.scrollbarInit(type);
                    $(document).click(windowClickHandler);
                } else {
                    gg.newProductFilter.isScrolling = false;
                    filter.displayElement.removeClass('active').next().hide();
                    $(document).unbind("click", windowClickHandler);
                }
                if (ev && ev.preventDefault) {
                    ev.preventDefault();
                }
            };
            filter.displayContainer.hover(function() {
                clearTimeout(delay);
                if ($("#" + type + "_content:hidden").length) {
                    delay = setTimeout(function() {
                        f("show");
                    }, 300);
                }
            }, function() {
                if (!gg.newProductFilter.isScrolling) {
                    clearTimeout(delay);
                    if ($("#" + type + "_content:visible").length) {
                        delay = setTimeout(function() {
                            f("hide");
                        }, 1000);
                    }
                }
            });
            filter.displayElement.click(function(ev) {
                f("toggle", ev);
            });
        })();
    }
    
    gg.newProductFilter.populate();

    gg.newProductFilter.restore();
};
gg.newProductFilter.store = function() {
    var isEmpty = true;
    for (var t in gg.newProductFilter.currentState) {
        if (gg.newProductFilter.currentState.hasOwnProperty(t)) {
            isEmpty = false;
            break;
        }
    }
    if (!isEmpty) {
        fl.LruCookie.store('product_filter', gg.newProductFilter.key, gg.newProductFilter.currentState);
    } else {
        fl.LruCookie.store('product_filter', gg.newProductFilter.key, null);
    }
};
gg.newProductFilter.restore = function() {
    var result = fl.LruCookie.fetch('product_filter', gg.newProductFilter.key);
    if (!result) {
        result = $.extend({}, gg.newProductFilter.defaultState);
    }
    gg.newProductFilter.currentState = result;

    gg.newProductFilter.process();
};
gg.newProductFilter.reset = function() {
    gg.newProductFilter.currentState = $.extend({}, gg.newProductFilter.defaultState);

    gg.newProductFilter.process();
};
gg.newProductFilter.track = function(type){
    var params = $.extend({}, gg.newProductFilter.currentState);
    params.type = "product";
    params.key = gg.newProductFilter.key;
    gg.TrackLog.record(type + "_filter", params);
};
gg.newProductFilter.scrollbarInit = function(dropdown) {
    if ($("#" + dropdown + '_scrollable')[0].scrollHeight > $("#" + dropdown + '_scrollable')[0].offsetHeight) {
        var range = $("#" + dropdown + '_scrollable')[0].scrollHeight - $("#" + dropdown + '_scrollable')[0].offsetHeight;
        $("#" + dropdown + "_track")
            .slider({
                orientation: 'vertical',
                value: (range - $("#" + dropdown + '_scrollable').scrollTop()) * 100 * range,
                slide: function(_, ui) {
                    $("#" + dropdown + '_scrollable').scrollTop(range - ui.value / 100 * range);
                },
                start: function() {
                    gg.productFilter.isScrolling = true;
                },
                stop: function() {
                    gg.productFilter.isScrolling = false;
                }
            })
            .find("img")
            .prependTo("#" + dropdown + "_track a");
    } else {
        $("#" + dropdown + '_track a img').prependTo("#" + dropdown + '_handle');
        $("#" + dropdown + "_track").slider("destroy");
    }
    $("#" + dropdown + '_handle').hide();
};

// Old Architecture
gg.productFilter = {
    type: '',
    key: '',
    hideSoldOutWithNullFilters: false,
    haveCategoryScrollContainer: true,
    categories: [],
    categoriesSizes: {},
    sizesCategories: {},
    currentState: {},
    persistent: false,
    storeStateAfterInit: true,
    elementSelector: '.product',
    saleId: '',
    isScrolling: false,
    allowMultipleFilters: false,
    addMouseoutHandlers: true,
    storeState: function() {
        log.setup("interaction", "product_filter")("Saving Filters");
        if (gg.productFilter.currentState.cat || gg.productFilter.currentState.sz || gg.productFilter.currentState.brand) {
            fl.LruCookie.store(gg.productFilter.type + '_filter', gg.productFilter.key, gg.productFilter.currentState);
        } else {
            fl.LruCookie.store(gg.productFilter.type + '_filter', gg.productFilter.key, null);
        }
    },
    fetchState: function(type,key) {
        log.setup("startup", "product_filter")("Retrieving Filters");
        var result = fl.LruCookie.fetch((type || gg.productFilter.type) + '_filter',
                                         key  || gg.productFilter.key);
        if (!result) {
            gg.productFilter.storeStateAfterInit = false;
            result = {};
        }
        return result;
    },
    populateCategories: function() {
        log.setup("interaction", "product_filter")("Populating Category Filter");
        var keys = [];
        if (gg.productFilter.currentState.sz) {
            var i = gg.productFilter.currentState.sz.length;
            while (i--) {
                var temp = gg.productFilter.sizesCategories[ gg.productFilter.currentState.sz[i] ];
                if (temp) {
                    var j = temp.length;
                    while (j--) {
                        if ($.inArray(temp[j], keys) == -1) {
                            keys.push(temp[j]);
                        }
                    }
                }
            }
        } else {
            keys = gg.productFilter.sizesCategories.all;
        }
        if (keys && keys.length) {
            keys.sort();
            var container = $('#categories');
            if (container.length) {
                container.html("<a id=\"all_categories\" " + (!gg.productFilter.currentState.cat ? 'class="selected" ' : '') + "onclick=\"gg.productFilter.clickCategory('all', this); return false;\" href=\"#\">All</a>");
                var selected = '';
                i = -1;
                var max = keys.length;
                var f = function(el) {
                    return function(ev){
                        var el = $(el||this);
                        gg.productFilter.clickCategory(el.id(), el);
                        ev.preventDefault();
                    };
                };
                while (++i < max) {
                    var item = keys[i];
                    //if (!$(".tab_brand").length || $(".tab_brand.selected").hasClass(item) ) {
                        selected = (gg.productFilter.currentState.cat && $.inArray(item, gg.productFilter.currentState.cat) != -1) ? ' class="selected"' : '';
                        var cat = $($.format("<a id=\"{0}\"{1} href=\"#\">{2}</a>", item, selected, gg.productFilter.categories[item]));
                        cat.click(f(cat));
                        container.append(cat);
                    //}
                }
            }
        } else {
            $("#category_scroll_container").hide(); // in rare instances, the data is incomplete, but the category dropdown is still visible -- in that situation, hide it
        }
    },
    populateSizes: function() {
        log.setup("interaction", "product_filter")("Populating Size Filter");
        var keys = [];
        if (gg.productFilter.currentState.cat) {
            var i = gg.productFilter.currentState.cat.length;
            while (i--) {
                var temp = gg.productFilter.categoriesSizes[ gg.productFilter.currentState.cat[i] ];
                if (temp) {
                    var j = -1;
                    var max = temp.length;
                    while (++j < max) {
                        if ($.inArray(temp[j], keys) == -1) {
                            keys.push(temp[j]);
                        }
                    }
                }
            }
        } else {
            keys = gg.productFilter.categoriesSizes.all;
        }
        var container = $('#sizes');
        if (container.length) {
            container.html("<a id=\"all_sizes\" " + (!gg.productFilter.currentState.sz ? 'class="selected" ' : '') + "onclick=\"gg.productFilter.clickSize('all', this); return false;\" href=\"#\">All</a>");
            var selected = '';
            i = -1;
            max = keys.length;
            var f = function(el) {
                return function(ev){
                    var el = $(el||this);
                    gg.productFilter.clickSize(el.id(), el);
                    ev.preventDefault();
                };
            };
            while (++i < max) {
                var item = keys[i];
                //if (!$(".tab_brand").length || $(".tab_brand.selected").hasClass(item) ) {
                    selected = (gg.productFilter.currentState.sz && $.inArray(item, gg.productFilter.currentState.sz) != -1) ? ' class="selected"' : '';
                    var size = $($.format("<a id=\"{0}\"{1} href=\"#\">{0}</a>", item, selected));
                    size.click(f(size));
                    container.append(size);
                //}
            }
        }
    },
    hideTitles: function() { // Deprecated???
        log.setup("interaction", "product_filter")("Hiding Brand Titles");
        $(".brand").hide()
            .next().children(":hidden")
            .parent().prev().show();
    },
    setTitles: function() {
        log.setup("interaction", "product_filter")("Setting Filter Titles");
        var newHtml;
        if (gg.productFilter.currentState.sz) {
            if (gg.productFilter.currentState.sz.length > 1) {
                newHtml = "Sizes: " + gg.productFilter.currentState.sz.join(", ");
            } else {
                newHtml = "Size: " + gg.productFilter.currentState.sz[0];
            }
            $('#size_filter_header').html(newHtml);
        } else {
            $('#size_filter_header').html('Size: All');
        }
        if (gg.productFilter.currentState.cat) {
            var i = -1;
            var max = gg.productFilter.currentState.cat.length;
            if (gg.productFilter.currentState.cat.length > 1) {
                newHtml = "Categories: ";
            } else {
                newHtml = "Category: ";
            }
            while (++i < max) {
                newHtml += gg.productFilter.categories[ gg.productFilter.currentState.cat[i] ] + ", ";
            }
            newHtml = newHtml.substr(0, newHtml.length - 2);
            if (newHtml.length > 30) {
                newHtml = newHtml.substr(0, 27) + "...";
            }
            $('#category_filter_header').html(newHtml);
        } else {
            $('#category_filter_header').html('Category: All');
        }
    },
    doTrackLog: function(clickType) {
        var params = $.extend({}, gg.productFilter.currentState);
        params.type = gg.productFilter.type;
        params.key = gg.productFilter.key;
        gg.TrackLog.record(clickType, params);
    },
    clickCategory: function(key, el, skip_tracking, init) {
        log.setup("interaction", "product_filter")("Filtering by Category: %s", key);
        $('#category_content').hide();
        if (!init) {
            if ('all' == key) {
                log("Removing Category Filter");
                delete gg.productFilter.currentState.cat;
                $('#categories a.selected').removeClass("selected");
            } else {
                if (gg.productFilter.allowMultipleFilters) {
                    if (el.hasClass("selected")) {
                        if ($.inArray(key, gg.productFilter.currentState.cat) != -1) {
                            gg.productFilter.currentState.cat.splice($.inArray(key, gg.productFilter.currentState.cat), 1);
                        }
                        el.removeClass("selected");
                        if (!gg.productFilter.currentState.cat.length) {
                            log("Removing Category Filter");
                            delete gg.productFilter.currentState.cat;
                            $("#all_categories").addClass("selected");
                        }
                    } else {
                        $("#all_categories").removeClass("selected");
                        if (!gg.productFilter.currentState.cat) {
                            gg.productFilter.currentState.cat = [];
                        }
                        if ($.inArray(key, gg.productFilter.currentState.cat) == -1) {
                            gg.productFilter.currentState.cat.push(key);
                        }
                        el.addClass("selected");
                    }
                } else {
                    gg.productFilter.currentState.cat = [key];
                }
            }
        }
        if (!gg.productFilter.allowMultipleFilters) {
            $('#categories a.selected').removeClass("selected");
            if (el.length) {
                el.addClass("selected");
            } else {
                $("#all_categories").addClass("selected");
            }
        }
        $('#category_content').hide();
        $('#category_filter_header').removeClass('active');
        gg.productFilter.populateSizes();
        gg.productFilter.process(el);
        gg.productFilter.setTitles();
        gg.productFilter.storeState();
        gg.productFilter.scrollbarInit("size");
        if (!skip_tracking) {
            gg.productFilter.doTrackLog('category_filter');
        }
    },
    clickSize: function(size, el, skip_tracking, init) {
        log.setup("interaction", "product_filter")("Filtering by Size: %d", size);
        $('#size_content').hide();
        if (!init) {
            if ('all' == size) {
                log("Removing Size Filter");
                delete gg.productFilter.currentState.sz;
                $('#sizes a.selected').removeClass('selected');
            } else {
                if (gg.productFilter.allowMultipleFilters) {
                    if (el.hasClass("selected")) {
                        if ($.inArray(size, gg.productFilter.currentState.sz) != -1) {
                            gg.productFilter.currentState.sz.splice($.inArray(size, gg.productFilter.currentState.sz), 1);
                        }
                        el.removeClass("selected");
                        if (!gg.productFilter.currentState.sz.length) {
                            log("Removing Size Filter");
                            delete gg.productFilter.currentState.sz;
                            $("#all_sizes").addClass("selected");
                        }
                    } else {
                        $("#all_sizes").removeClass("selected");
                        if (!gg.productFilter.currentState.sz) {
                            gg.productFilter.currentState.sz = [];
                        }
                        if ($.inArray(size, gg.productFilter.currentState.sz) == -1) {
                            gg.productFilter.currentState.sz.push(size);
                        }
                        el.addClass("selected");
                    }
                } else {
                    gg.productFilter.currentState.sz = [size];
                }
            }
        }
        if (!gg.productFilter.allowMultipleFilters) {
            $('#sizes a.selected').removeClass("selected");
            if (el.length) {
                el.addClass("selected");
            } else {
                $("#all_sizes").addClass("selected");
            }
        }
        $('#size_content').hide();
        $('#size_filter_header').removeClass('active');
        gg.productFilter.populateCategories();
        gg.productFilter.process(el);
        gg.productFilter.setTitles();
        gg.productFilter.storeState();
        gg.productFilter.scrollbarInit("category");
        if (!skip_tracking) {
            gg.productFilter.doTrackLog('size_filter');
        }
    },
    process: function(selected_el) {
        log.setup("interaction", "product_filter")("Applying Filters");
        var products = $(gg.productFilter.elementSelector);
        var size = gg.productFilter.currentState.sz;
        var key = gg.productFilter.currentState.cat;
        //var brand = gg.productFilter.currentState.brand;
        var attributes = [];
        if (size) {
            log("Size Filter Active");
            attributes.push(size);
        }
        if (key) {
            log("Category Filter Active");
            attributes.push(key);
        }
        /*if (brand) {
            log("Brand Filter Active");
            attributes.push(brand);
        }*/
        //$(selected_el).addClass("selected");

        var i = products.length;
        while (i--) {
            var product = products.eq(i);
            var show = true;
            var j = attributes.length;
            while (j--) {
                var anyof = attributes[j];
                var k = anyof.length;
                var found = false;
                while (k--) {
                    if (product.hasClass(anyof[k].replace(".", "\\."))) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    show = false;
                    break;
                }
                /*if (!product.hasClass(attributes[j])) {
                    *//*if (attributes[j] == gg.productFilter.currentState.brand && product.hasClass(".tab_brand")) {
                        continue; // don't filter brands by brand
                    }*//*
                    show = false;
                    break;
                }*/
            }

            if (show && product.hasClass('filter_look_sold_out') && (attributes.length || gg.productFilter.hideSoldOutWithNullFilters)) {
                show = false;
            }

            if (show) {
                log("Showing Product #%d", product[0].id);
                product.show();
            } else {
                log("Hiding Product #%d", product[0].id);
                product.hide();
            }
        }

        if (!$("#catalog .product:visible").length) { // Show a message if everything in the current filter is sold out
            $("#all_sold_out").show();
        } else {
            $("#all_sold_out").hide();
        }

        if ($("#catalog .product:visible").length >= parseInt($("#back_to_top").attr("reqlooks"))) { // Hide the back to top link if too few products are visible
            $("#back_to_top").show();
        } else {
            $("#back_to_top").hide();
        }

        //if ($(".brand_button:visible").length && !$(".brand_button.selected:visible").length) { // current tab got hidden, select the first visible one
        //    document.location = $(".brand_button:visible:first").attr("href");
        //}
        gg.productFilter.hideTitles();
        $(document).trigger("catalogchanged");
        log("Done Applying Filters");
    },
    scrollbarInit: function(dropdown) {
        if ($.browser.msie && 7 > parseInt($.browser.version)) {
          $("#" + dropdown + '_track img').hide();
          return;
        }
        var scrollable = $("#" + dropdown + '_scrollable');
        if(scrollable.length) {
            if (scrollable.children("div.drop_down_content").height() > parseInt(scrollable.css("max-height"))) {
                var range = scrollable.children("div.drop_down_content").height() - parseInt(scrollable.css("max-height"));
                scrollable.css("height", scrollable.css("max-height"));
                $("#" + dropdown + "_track")
                    .slider({
                        orientation: 'vertical',
                        value: 100,
                        slide: function(_, ui) {
                            scrollable.scrollTop(range - ui.value / 100 * range);
                        },
                        start: function() {
                            gg.productFilter.isScrolling = true;
                        },
                        stop: function() {
                            gg.productFilter.isScrolling = false;
                        }
                    })
                    .find("img")
                    .prependTo("#" + dropdown + "_track a");
            } else {
                scrollable.css("height", "");
                $("#" + dropdown + '_track a img').prependTo("#" + dropdown + '_handle');
                $("#" + dropdown + "_track").slider("destroy");
            }
            $("#" + dropdown + '_handle').hide();
        }
    },
    init: function(hideSoldOutWithNullFilters) {
        gg.newProductFilter = false;
        log.setup("startup", "product_filter")("Initializing Product Filters");
        gg.productFilter.hideSoldOutWithNullFilters = hideSoldOutWithNullFilters;

        if (gg.productFilter.addMouseoutHandlers) {
            $("#category_scroll_container, #size_scroll_container").unbind("mouseout");
            if (gg.productFilter.haveCategoryScrollContainer) {
                $("#category_scroll_container").mouseout(function(ev) {
                    if (!gg.productFilter.isScrolling && !$(ev.relatedTarget).closest("#category_scroll_container").length) {
                        $('#category_content').hide();
                        $('#category_filter_header').removeClass('active');
                    }
                });
            }

            $('#size_scroll_container').mouseout(function(ev) {
                if (!gg.productFilter.isScrolling && !$(ev.relatedTarget).closest('#size_scroll_container').length) {
                    $('#size_content').hide();
                    $('#size_filter_header').removeClass('active');
                }
            });
        }


        fl.LruCookie.setPersist(gg.productFilter.type + '_filter', gg.productFilter.persistent);
        fl.LruCookie.setMaxSize(gg.productFilter.type + '_filter', 128);

        gg.productFilter.currentState = gg.productFilter.fetchState();

        // Figure out current category, using cookie if present
        var cookie_categories = gg.productFilter.currentState.cat;
        if (cookie_categories) {
            var i = cookie_categories.length;
            while (i--) {
                if (!gg.productFilter.categories[cookie_categories[i]]) {
                    cookie_categories.splice(i, 1);
                }
            }
            if (!cookie_categories.length) {
                delete gg.productFilter.currentState.cat;
                cookie_categories = null;
                gg.productFilter.populateSizes();
            }
        } else {
            delete gg.productFilter.currentState.cat;
            gg.productFilter.populateSizes();
        }

        // Figure out current size, using cookie if present
        var cookie_sizes = gg.productFilter.currentState.sz;
        if (cookie_sizes) {
            i = cookie_sizes.length;
            while (i--) {
                var legal_size = false;
                if (cookie_categories) {
                var j = cookie_categories.length;
                    while (j--) {
                        var catsizes = gg.productFilter.categoriesSizes[ cookie_categories[i] ];
                        if (catsizes) {
                            var k = catsizes.length;
                            while (k--) {
                                if (catsizes[k] == cookie_sizes[i]) {
                                    legal_size = true;
                                    break;
                                }
                            }
                            if (legal_size) {
                                break;
                            }
                        }
                    }
                } else {
                    catsizes = gg.productFilter.categoriesSizes[ 'all' ];
                    if (catsizes) {
                        k = catsizes.length;
                        while (k--) {
                            if (catsizes[k] == cookie_sizes[i]) {
                                legal_size = true;
                                break;
                            }
                        }
                        if (legal_size) {
                            break;
                        }
                    }
                }
                if (!legal_size) {
                    cookie_sizes.splice(i, 1);
                }
            }
            if (!cookie_sizes.length) {
                delete gg.productFilter.currentState.sz;
                cookie_sizes = null;
                gg.productFilter.populateCategories();
            }
        } else {
            delete gg.productFilter.currentState.sz;
            gg.productFilter.populateCategories();
        }

        if (cookie_categories) {
            i = cookie_categories.length;
            while (i--) {
                gg.productFilter.clickCategory(cookie_categories[i], $("#" + cookie_categories[i]), true, true);
            }
        }

        if (cookie_sizes) {
            i = cookie_sizes.length;
            while (i--) {
                gg.productFilter.clickSize(cookie_sizes[i], $("#" + cookie_sizes[i]), true, true);
            }
        }

        if (gg.productFilter.storeStateAfterInit) {
            gg.productFilter.storeState();
        }

        if (!$("#catalog .product:visible").length) { // Show a message if everything in the current brand is sold out
            $("#all_sold_out").show();
        } else {
            $("#all_sold_out").hide();
        }

        if ($("#catalog .product:visible").length >= parseInt($("#back_to_top").attr("reqlooks"))) { // Hide the back to top link if too few products are visible
            $("#back_to_top").show();
        } else {
            $("#back_to_top").hide();
        }

        log("Product Filter Initialization Complete");
    }
};

var Gilt;
if (!Gilt) {
  Gilt = {};
}

Gilt.SingleSignOnLinks = {};

function identify_domain_name(hostname) {
  var re_is_prod = /^(www.|admin.gilt.)/;
  var re_fuse_dev_qa = /^fuse/;
  var re_man_dev_qa = /^man/;
  var re_admin_dev_qa = /^admin/;
  var re_fuse_prod = /^www.giltfuse.com/;
  var re_man_prod = /^www.giltman.com/;
  var re_admin_prod = /^admin.gilt.com/;
  if ( re_is_prod.test(hostname) ) { // Then we are on prod
    // Get the proper domain name from production hostnames
    if ( re_fuse_prod.test(hostname) ) {
      return "fuse";
    }
    else if ( re_man_prod.test(hostname) ) {
        return "man";
    }
    else if ( re_admin_prod.test(hostname) ) {
        return "admin";
    }
    else {
      return "gilt";
    }
  }
  else {
    // Get the proper domain name from dev and qa
    if ( re_fuse_dev_qa.test(hostname) ) {
      return "fuse";
    }
    else if( re_man_dev_qa.test(hostname) ) {
      return "man";
    }
    else if( re_admin_dev_qa.test(hostname) ) {
      return "admin";
    }
    else {
      return "gilt";
    }
  }
}

Gilt.SingleSignOnLinks.init = function() {
  $.each(Gilt.SingleSignOnLinks.Subsites, function(hostname, id) {
    $('a[href*="http://' + hostname + '"]')
      .click(function(ev) {
        if(!$(this).hasClass('no_sso')) {
          ev.preventDefault();
          Gilt.SingleSignOnLinks.buildPostLink(hostname, $(this).attr('href'), $(this));
        }
      });
  });
};

Gilt.SingleSignOnLinks.appendToForm = function(sso_form, cookie_name, element_id) {
  if ("undefined" == typeof element_id) {
    element_id = cookie_name;
  }
  if (fl.Util.readCookie(cookie_name)) {
    sso_form.append("<input type='hidden' id='" + element_id + "' name='" + element_id + "' value='" + escape(fl.Util.readCookie(cookie_name)) + "' />");
  }
};

// Build and submit sso request as a form post
Gilt.SingleSignOnLinks.buildPostLink = function(hostname, redirectURL, link) {
  var parsedURL = $.url.setUrl(redirectURL);
  var redirectPath = parsedURL.attr('path') || "";
  if (Gilt.SingleSignOnLinks.ServerPort) hostname += ':' + Gilt.SingleSignOnLinks.ServerPort;

  // Note: cookie_guid and cookie_guid_entire here only for tracing purposes to be
  // able to watch one guid through all the zeus access logs
  var url = document.location.protocol + '//' + hostname + '/sso?cookie_guid=' + escape(fl.Util.readHashedCookie('guid')) + '&cookie_guid_entire=' + escape(fl.Util.readCookie('guid_entire'));

  // Build the Form
  var sso_form = $("<form action='" + url + "' method='post' />");

  if (link && link[0] && link[0].target == '_blank') {
    sso_form[0].target = '_blank';
  }

  Gilt.SingleSignOnLinks.appendToForm(sso_form,'guid_entire','guid');
  Gilt.SingleSignOnLinks.appendToForm(sso_form,'cid');
  Gilt.SingleSignOnLinks.appendToForm(sso_form,'pt');
  var pathAndQuery = escape(redirectPath);
  var query = parsedURL.attr('query');
  if (query) {
      pathAndQuery += '?';
      pathAndQuery += query;
  }
  sso_form.append("<input type='hidden' id='redirectURL' name='redirectURL' value='" + pathAndQuery + "' />");
  sso_form.append("<input type='hidden' name='notifications' value='" + fl.Util.readCookie('notifications') + "' />");
  sso_form.append("<input type='hidden' name='ssni' value='" + fl.Util.readCookie('ssni') + "' />");
  $("body").append(sso_form);
  sso_form.submit();
};

// Copyright 2009 Gilt Groupe, Inc.

var gg;
if (!gg) gg = {};

gg.Diagnostics = {};

// Check for everything
gg.Diagnostics.run = function(sessionCookieName, persistentCookieName) {
	gg.Diagnostics.javascript();
	gg.Diagnostics.sessionCookies(sessionCookieName);
	gg.Diagnostics.persistantCookies(persistentCookieName);
};

// Check if user javascript is enable
gg.Diagnostics.javascript = function() {
	document.getElementById('JavaScript').innerHTML="<p><strong>Javascript is enabled.</strong></p>";
};

// Check if user persistant cookies is enable
gg.Diagnostics.persistantCookies = function(cookieName) {
	 if (fl.Util.readCookie(cookieName)) {
	 	document.getElementById('PersistentCookies').innerHTML="<p><strong>Persistent cookies are enabled.</strong></p>";
	 }
};

// Check if user session cookies is enable
gg.Diagnostics.sessionCookies = function(cookieName) {
	if (fl.Util.readCookie(cookieName)) {
	    document.getElementById('SessionCookies').innerHTML="<p><strong>Session cookies are enabled.<strong></p>";
	}
};

var Gilt;
if (!Gilt) {
  Gilt = { };
}

Gilt.Logout = {};

// Logs one out of the gilt website by unsetting the login cookies
Gilt.Logout.go = function(redirectURL, clearAllCookies) {
  var cookies_to_keep = {};
  if (!clearAllCookies) {
    // Cookies to keep hash
    cookies_to_keep = {
      cp: "Used for AB Testing - keep this around (zeus would set it anyway if missing",
      email: "Used to prefill the login form when members come back to the site",
      gender: "Used to display various imagery on the site",
      usermeta: "Needed for remember me value",
      asc: "This cookie is only used to authorize access once every few months"
    };
  }

  var document_cookies = document.cookie.split(';'); // Get all document cookis

  // For each document cookie determine if it needs to be deleted.
  $.each(document_cookies, function() {
      var cracked_cookie = this.split('=');
      cracked_cookie[0] = cracked_cookie[0].replace(/^\s*([\S\s]*?)\s*$/, '$1'); // Trim off any whitespace
      if (!cookies_to_keep.hasOwnProperty(cracked_cookie[0])) {
        fl.Util.expireCookie(cracked_cookie[0]);
      }
  });

  // Redirect to the specified redirectURL
  if (!redirectURL) {
    redirectURL = "/";
  }
  window.location = redirectURL;
};

/* SiteCatalyst code version: H.17.
Copyright 1997-2008 Omniture, Inc. More info available at
http://www.omniture.com */
/************************ ADDITIONAL FEATURES ************************
     Plugins
*/
var s_account="gggiltgroupecomdev";
var s=s_gi(s_account);
/************************** CONFIG SECTION **************************/
/* You may add or alter any code config here. */
/* Conversion Config */
s.currencyCode="USD";
/* Link Tracking Config */
s.trackDownloadLinks=true;
s.trackExternalLinks=true;
s.trackInlineStats=true;
s.linkDownloadFileTypes="exe,zip,wav,mp3,mov,mpg,avi,wmv,pdf,doc,docx,xls,xlsx,ppt,pptx";
s.linkInternalFilters="javascript:,gilt.com,giltfuse.com,giltman.com,localhost";
s.linkLeaveQueryString=false;
s.linkTrackVars="None";
s.linkTrackEvents="None";
s.dynamicAccountSelection=true;
s.dynamicAccountList = 'gggiltgroupecomprod=www.gilt.com;gggiltfusecomprod=www.giltfuse.com;gggiltmobilecomprod=m.gilt.com;gggiltmancomprod=www.giltman.com;gggiltmancomdev=man.qa.gilt.com;gggiltmancomdev=man.localhost;gggiltfusecomdev=fuse.qa.gilt.com;gggiltfusecomdev=fuse.localhost';
s.trackingServer='stat.gilt.com';
s.trackingServerSecure='sstat.gilt.com';
/* Plugin Config */
s.usePlugins=true;

s.successfulSearchEvent 		= 'event1';
s.nullSearchEvent 				= 'event2';
s.searchTermVariable		    = 'eVar1';

function s_doPlugins(s) {
	if(!s.campaign)
		s.campaign=s.getQueryParam('pkey');

	if(!s.eVar2)
		s.eVar2=s.getQueryParam('INTCMP');
	
	if(s.eVar1) 
		s.eVar1=s.eVar1.toLowerCase();

	/*
	 * Do not refire search event if the same search term
	 * passed in twice
	*/
	var t_search=s.getValOnce(s[s.searchTermVariable],'ev1',0);
	if(t_search=='')
	{	
		var a=s.split(s.events,',');
		var e='';
		for(var i = 0; i < a.length ; i++ )
		{
			if(a[i] == s.successfulSearchEvent)
				continue;
			else if(a[i] == s.nullSearchEvent)
				continue;
			else
				e += a[i]?a[i]+',':a[i];
		}
		s.events=e.substring(0,e.length-1);
	}
	else
	{
		if(!s.products)
			s.products=';';
	}

}
s.doPlugins=s_doPlugins;
/************************** PLUGINS SECTION *************************/
/* You may insert any plugins you wish to use here.                 */
/*
 * Plugin: getQueryParam 2.1 - return query string parameter(s)
 */
s.getQueryParam=new Function("p","d","u",""
+"var s=this,v='',i,t;d=d?d:'';u=u?u:(s.pageURL?s.pageURL:s.wd.locati"
+"on);if(u=='f')u=s.gtfs().location;while(p){i=p.indexOf(',');i=i<0?p"
+".length:i;t=s.p_gpv(p.substring(0,i),u+'');if(t)v+=v?d+t:t;p=p.subs"
+"tring(i==p.length?i:i+1)}return v");
s.p_gpv=new Function("k","u",""
+"var s=this,v='',i=u.indexOf('?'),q;if(k&&i>-1){q=u.substring(i+1);v"
+"=s.pt(q,'&','p_gvf',k)}return v");
s.p_gvf=new Function("t","k",""
+"if(t){var s=this,i=t.indexOf('='),p=i<0?t:t.substring(0,i),v=i<0?'T"
+"rue':t.substring(i+1);if(p.toLowerCase()==k.toLowerCase())return s."
+"epa(v)}return ''");

/*
 * Plugin: getCookieParam 0.1 - fetch a param from a cookie
 */
s.getCookieParam=function(param) {
  var cookie = fl.Util.readCookie(param);
  fl.Util.expireCookie(param);
  return cookie;
}

/*
 * Plugin: getValOnce 0.2 - get a value once per session or number of days
 */
s.getValOnce=new Function("v","c","e",""
+"var s=this,k=s.c_r(c),a=new Date;e=e?e:0;if(v){a.setTime(a.getTime("
+")+e*86400000);s.c_w(c,v,e?a:0);}return v==k?'':v");

/*
 * Utility Function: split v1.5 - split a string (JS 1.0 compatible)
 */
s.split=new Function("l","d",""
+"var i,x=0,a=new Array;while(l){i=l.indexOf(d);i=i>-1?i:l.length;a[x"
+"++]=l.substring(0,i);l=l.substring(i+d.length);}return a");




/* WARNING: Changing any of the below variables will cause drastic
changes to how your visitor data is collected.  Changes should only be
made when instructed to do so by your account manager.*/
s.visitorNamespace="giltgroupe";
s.dc=122;

/************* DO NOT ALTER ANYTHING BELOW THIS LINE ! **************/
var s_code='',s_objectID;function s_gi(un,pg,ss){var c="=fun@6(~){`Ks=^S~$h ~.substring(~.indexOf(~;@t~';`Bt`t~=new Fun@6(~.toLowerCase()~s_c_il['+s^sn+']~};s.~`m@t~.length~.toUpperCase~=new Object~s"
+".wd~','~){@t~')q='~.location~var ~s.pt(~dynamicAccount~link~s.apv~='+@y(~)@tx^m!Object$eObject.prototype$eObject.prototype[x])~);s.~Element~.getTime()~=new Array~ookieDomainPeriods~s.m_~referrer~.p"
+"rotocol~=new Date~BufferedRequests~}c$s(e){~visitor~;@X^js[k],255)}~=''~javaEnabled~conne@6^M~@0c_i~Name~:'')~onclick~}@t~else ~ternalFilters~javascript~s.dl~@Os.b.addBehavior(\"# default# ~=parseF"
+"loat(~'+tm.get~=='~cookie~s.rep(~s.^T~track~o@0oid~browser~.parent~window~colorDepth~String~while(~.host~.lastIndexOf('~s.sq~s.maxDelay~s.vl_g~r=s.m(f)?s[f](~for(~s.un~s.eo~&&s.~parseInt(~t=s.ot(o)"
+"~j='1.~#4URL~lugins~dynamicVariablePrefix~document~Type~Sampling~s.rc[un]~Download~Event~');~this~tfs~resolution~s.c_r(~s.c_w(~s.eh~s.isie~s.vl_l~s.vl_t~Height~t,h){t=t?t~tcf~isopera~ismac~escape(~"
+".href~screen.~s.fl(~Version~harCode~&&(~_'+~variableProvider~s.pe~)?'Y':'N'~:'';h=h?h~._i~e&&l$HSESSION'~f',~onload~name~home#4~objectID~}else{~.s_~s.rl[u~Width~s.ssl~o.type~Timeout(~ction~Lifetime"
+"~.mrq(\"'+un+'\")~sEnabled~;i++)~'){q='~&&l$HNONE'){~ExternalLinks~charSet~onerror~lnk~currencyCode~.src~s=s_gi(~etYear(~&&!~Opera~'s_~;try{~Math.~s.fsg~s.ns6~s.oun~InlineStats~Track~'0123456789~&&"
+"t~s[k]=~s.epa(~m._d~n=s.oid(o)~,'sqs',q);~LeaveQuery~')>=~'=')~)+'/~){n=~\",''),~vo)~s.sampled~=s.oh(o);~+(y<1900?~s.disable~ingServer~n]=~true~sess~campaign~lif~if(~'http~,100)~s.co(~x in ~s.ape~f"
+"fset~s.c_d~s.br~'&pe~s.gg(~s.gv(~s[mn]~s.qav~,'vo~s.pl~=(apn~Listener~\"s_gs(\")~vo._t~b.attach~d.create~=s.n.app~(''+~!='~'||t~'+n~s()+'~){p=~():''~a):f(~+1))~a['!'+t]~){v=s.n.~channel~un)~.target"
+"~o.value~g+\"_c\"]~\".tl(\")~etscape~(ns?ns:~s_')t=t~k',s.bc~omePage~s.d.get~')<~||!~[b](e);~m[t+1](~return~mobile~height~events~random~code~'MSIE ~rs,~un,~,pev~floor(~atch~s.num(~[\"s_\"+~s.c_gd~s"
+".dc~s.pg~,'lt~.inner~transa~;s.gl(~\"m_\"+n~idt='+~page~Group,~.fromC~sByTag~?'&~+';'~t&&~1);~){s.~[t]=~>=5)~[t](~=l[n];~!a[t])~~s._c=@Nc';`F=^1`5!`F`hn){`F`hl`U;`F`hn=0;}s^sl=`F`hl;s^sn=`F`hn;s^sl"
+"[s^s@os;`F`hn++;s.m`0m){`2$Gm)`4'{$d0`Afl`0x,l){`2x?$Gx)`30,l):x`Aco`0o`H!o)`2o;`Kn`E,x;^B@xo)@tx`4'select$d0&&x`4'filter$d0)n[x]=o[x];`2n`Anum`0x){x`e+x;^B`Kp=0;p<x`C;p++)@t(@V')`4x`3p,p$O<0)`20;`"
+"21`Arep=s_r;@y`0x`1,h=@VABCDEF',i,c=s.@E,n,l,e,y`e;c=c?c`D$M`5x){x`e+x`5c`tAUTO'^m'').c^lAt){^Bi=0;i<x`C@A{c=x`3i,i+#Bn=x.c^lAt(i)`5n>127){l=0;e`e;^4n||l<4){e=h`3n%16,n%16+1)+e;n=(n-n%16)/16;l++}y+"
+"='%u'+e}`Bc`t+')y+='%2B';`my+=^gc)}x=y^zx=x?`v^g''+x),'+`G%2B'):x`5x&&c^Eem==1&&x`4'%u$d0&&x`4'%U$d0){i=x`4'%^R^4i>=0){i++`5h`38)`4x`3i,i+1)`D())>=0)`2x`30,i)+'u00'+x`3i);i=x`4'%',i)}}}}`2x`Aepa`0x"
+"`1;`2x?un^g`v''+x,'+`G ')):x`Apt`0x,d,f,a`1,t=x,z=0,y,r;^4t){y=t`4d);y=y<0?t`C:y;t=t`30,y);^At,$Nt,a)`5r)`2r;z+=y+d`C;t=x`3z,x`C);t=z<x`C?t:''}`2''`Aisf`0t,a){`Kc=a`4':')`5c>=0)a=a`30,c)`5t`30,2)`t"
+"$Z`32);`2(t!`e@W==a)`Afsf`0t,a`1`5`La,`G,'is^ut))@Q+=(@Q!`e?`G`j+t;`20`Afs`0x,f`1;@Q`e;`Lx,`G,'fs^uf);`2@Q`Ac_d`e;$vf`0t,a`1`5!$tt))`21;`20`Ac_gd`0`1,d=`F`J^5^w,n=s.fpC`V,p`5!n)n=s.c`V`5d@L$0@gn?^F"
+"n):2;n=n>2?n:2;p=d^6.')`5p>=0){^4p>=0&&n>1$Ld^6.',p-#Bn--}$0=p>0&&`Ld,'.`Gc_gd^u0)?d`3p):d}}`2$0`Ac_r`0k`1;k=@y(k);`Kc=' '+s.d.`u,i=c`4' '+k+@e,e=i<0?i:c`4';',i),v=i<0?'':@Yc`3i+2+k`C,e<0?c`C:e));`"
+"2v$H[[B]]'?v:''`Ac_w`0k,v,e`1,d=$v(),l=s.`u@7,t;v`e+v;l=l?$Gl)`D$M`5^t@Ct=(v!`e?^Fl?l:0):-60)`5t){e`Z;e.setTime(e`T+(t*1000))}`lk@Cs.d.`u=k+'`Pv!`e?v:'[[B]]')+'; path=/;'+(^t?' expires='+e.toGMT^3("
+")#9`j+(d?' domain='+d#9`j;`2^Vk)==v}`20`Aeh`0o,e,r,f`1,b='s^ne+'^ns^sn,n=-1,l,i,x`5!^Xl)^Xl`U;l=^Xl;^Bi=0;i<l`C&&n<0;i++`Hl[i].o==o&&l[i].e==e)n=i`ln<0@gi;l[n]`E}x#Gx.o=o;x.e=e;f=r?x.b:f`5r||f){x.b"
+"=r?0:o[e];x.o[e]=f`lx.b){x.o[b]=x.b;`2b}`20`Acet`0f,a,t,o,b`1,r,^d`5`O>=5^m!s.^e||`O>=7)){^d`7's`Gf`Ga`Gt`G`Ke,r@O^A$Na)`br=s.m(t)?s#Fe):t(e)}`2r^Rr=^d(s,f,a,t)^z@ts.^f^Eu`4$n4@d0)r=s.m(b)?s[b](a):"
+"b(a);else{^X(`F,'@F',0,o);^A$Na`Reh(`F,'@F',1)}}`2r`Ag^Tet`0e`1;`2`w`Ag^Toe`7'e`G`Ks=`9,c;^X(^1,\"@F\",1`Re^T=1;c=s.t()`5c)s.d.write(c`Re^T=0;`2@p'`Rg^Tfb`0a){`2^1`Ag^Tf`0w`1,p=w^0,l=w`J;`w=w`5p&&p"
+"`J!=l&&p`J^5==l^5){`w=p;`2s.g^Tf(`w)}`2`w`Ag^T`0`1`5!`w){`w=`F`5!s.e^T)`w=s.cet('g^T^u`w,'g^Tet',s.g^Toe,'g^Tfb')}`2`w`Amrq`0u`1,l=@1],n,r;@1]=0`5l)^Bn=0;n<l`C;n++){r#Gs.mr(0,0,r.r,0,r.t,r.u)}`Abr`"
+"0id,rs`1`5@m`a$e^W@Nbr',rs))$1l=rs`Aflush`a`0`1;s.fbr(0)`Afbr`0id`1,br=^V@Nbr')`5!br)br=$1l`5br`H!@m`a)^W@Nbr`G'`Rmr(0,0,br)}$1l=0`Amr`0@q,q,$oid,ta,u`1,dc=$w,t1=s.`x@n,t2=s.`x@nSecure,ns=s.`c`ispa"
+"ce,un=u?u:$Ys.f$S,unc=`v$p'_`G-'),r`E,l,imn=@Ni^n($S,im,b,e`5!rs){rs=@u'+(@3?'s'`j+'://'+(t1?(@3@W2?t2:t1):($Y(@3?'102':unc))+'.'+($w?$w:112)+'.2o7.net')@fb/ss/'+^C+'/'+(s.$i?'5.1':'1'@fH.17/'+@q+'"
+"?AQB=1&ndh=1'+(q?q`j+'&AQE=1'`5^Y@Ls.^f`H`O>5.5)rs=^j$o4095);`mrs=^j$o2047)`lid){$1(id,rs);$h}`ls.d.images&&`O>=3^m!s.^e||`O>=7)^m@R<0||`O>=6.1)`H!s.rc)s.rc`E`5!^O){^O=1`5!s.rl)s.rl`E;@1n]`U;set@5'"
+"@t^1`hl)^1.`9@8',750)^zl=@1n]`5l){r.t=ta;r.u=un;r.r=rs;l[l`C]=r;`2''}imn+='^n^O;^O++}im=`F[imn]`5!im)im=`F[im@onew Image;im@0l=0;im.^v`7'e`G^S@0l=1`5^1`hl)^1.`9@8^Rim@I=rs`5rs`4$2=@d0^m!ta||ta`t_se"
+"lf$Ia`t_top'||(`F.^w@Wa==`F.^w))){b=e`Z;^4!im@0l&&e`T-b`T<500)e`Z}`2''}`2'<im'+'g sr'+'c=\"'+rs+'\" width=1 $j=1 border=0 alt=\"\">'`Agg`0v`1`5!`F['s^nv])`F['s^nv]`e;`2`F['s^nv]`Aglf`0t,a`Ht`30,2)`"
+"t$Z`32);`Ks=^S,v=$3t)`5v)s#Dv`Agl`0v`1`5$x)`Lv,`G,'gl^u0)`Agv`0v`1;`2s['vpm^nv]?s['vpv^nv]:(s[v]?s[v]`j`Ahavf`0t,a`1,b=t`30,4),x=t`34),n=^Fx),k='g^nt,m='vpm^nt,q=t,v=s.`N@UVa$oe=s.`N@U^Qs,mn;@X$4t)"
+"`5s.@G||^D||^p`H^p^Epe`30,4)$H@G_'){mn=^p`30,1)`D()+^p`31)`5$5){v=$5.`xVars;e=$5.`x^Qs}}v=v?v+`G+^Z+`G+^Z2:''`5v@L`Lv,`G,'is^ut))s[k]`e`5t`t$k'&&e)@Xs.fs(s[k],e)}s[m]=0`5t`t^K`ID`6`cID`Ivid`6^I@Bg'"
+"`d`Bt`t`X@Br'`d`Bt`tvmk`Ivmt`6@E@Bce'`5s[k]&&s[k]`D()`tAUTO')@X'ISO8859-1';`Bs[k]^Eem==2)@X'UTF-8'}`Bt`t`c`ispace`Ins`6c`V`Icdp`6`u@7`Icl`6^o`Ivvp`6@H`Icc`6$R`Ich`6#0@6ID`Ixact`6@r`Iv0`6^U`Is`6^2`I"
+"c`6`o^k`Ij`6`f`Iv`6`u@9`Ik`6`z@2`Ibw`6`z^b`Ibh`6`g`Ict`6^x`Ihp`6p^J`Ip';`B$tx)`Hb`tprop`Ic$J;`Bb`teVar`Iv$J;`Bb`thier@Bh$J`d`ls[k]@W$H`N`i'@W$H`N^M')$6+='&'+q+'`Ps[k]);`2''`Ahav`0`1;$6`e;`L^a,`G,'h"
+"av^u0);`2$6`Alnf`0^c`8^r`8:'';`Kte=t`4@e`5t@We>0&&h`4t`3te$O>=0)`2t`30,te);`2''`Aln`0h`1,n=s.`N`is`5n)`2`Ln,`G,'ln^uh);`2''`Altdf`0^c`8^r`8:'';`Kqi=h`4'?^Rh=qi>=0?h`30,qi):h`5#Ah`3h`C-(t`C$O`t.'+t)"
+"`21;`20`Altef`0^c`8^r`8:''`5#Ah`4t)>=0)`21;`20`Alt`0h`1,lft=s.`N^PFile^Ms,lef=s.`NEx`n,@s=s.`NIn`n;@s=@s?@s:`F`J^5^w;h=h`8`5s.`x^PLinks&&lf#A`Llft,`G$yd^uh))`2'd'`5s.`x@D&&h`30,1)$H# '^mlef||@s)^m!"
+"lef||`Llef,`G$ye^uh))^m!@s$e`L@s,`G$ye^uh)))`2'e';`2''`Alc`7'e`G`Ks=`9,b=^X(^S,\"`k\"`R@G=@w^S`Rt(`R@G=0`5b)`2^S$f`2@p'`Rbc`7'e`G`Ks=`9,f,^d`5s.d^Ed.all^Ed.all.cppXYctnr)$h;^D=e@I`S?e@I`S:e$T;^d`7"
+"\"s\",\"`Ke@O@t^D^m^D.tag`i||^D^0`S||^D^0Node))s.t()`b}\");^d(s`Reo=0'`Roh`0o`1,l=`F`J,h=o^h?o^h:'',i,j,k,p;i=h`4':^Rj=h`4'?^Rk=h`4'/')`5h^mi<0||(j>=0&&i>j)||(k>=0&&i>k))$Lo`Y&&o`Y`C>1?o`Y:(l`Y?l`Y"
+"`j;i=l.path^w^6/^Rh=(p?p+'//'`j+(o^5?o^5:(l^5?l^5`j)+(h`30,1)$H/'?l.path^w`30,i<0?0:i@f'`j+h}`2h`Aot`0o){`Kt=o.tag`i;t=t@W`D?t`D$M`5t`tSHAPE')t`e`5t`Ht`tINPUT'&&@4&&@4`D)t=@4`D();`B!#Ao^h)t='A';}`2"
+"t`Aoid`0o`1,^G,p,c,n`e,x=0`5t@L`y$Lo`Y;c=o.`k`5o^h^mt`tA$I`tAREA')^m!c$ep||p`8`4'`o$d0))n@k`Bc@g`vs.rep(`vs.rep$Gc,\"\\r@h\"\\n@h\"\\t@h' `G^Rx=2}`B$U^mt`tINPUT$I`tSUBMIT')@g$U;x=3}`Bo@I@W`tIMAGE')"
+"n=o@I`5n){`y=^jn@v;`yt=x}}`2`y`Arqf`0t,un`1,e=t`4@e,u=e>=0?`G+t`30,e)+`G:'';`2u&&u`4`G+un+`G)>=0?@Yt`3e$O:''`Arq`0un`1,c=un`4`G),v=^V@Nsq'),q`e`5c<0)`2`Lv,'&`Grq^u$S;`2`L$p`G,'rq',0)`Asqp`0t,a`1,e="
+"t`4@e,q=e<0?'':@Yt`3e+1)`Rsqq[q]`e`5e>=0)`Lt`30,e),`G@b`20`Asqs`0$pq`1;^7u[u@oq;`20`Asq`0q`1,k=@Nsq',v=^Vk),x,c=0;^7q`E;^7u`E;^7q[q]`e;`Lv,'&`Gsqp',0);`L^C,`G@bv`e;^B@x^7u`Q)^7q[^7u[x]]+=(^7q[^7u[x"
+"]]?`G`j+x;^B@x^7q`Q&&^7q[x]^mx==q||c<2)){v+=(v#8'`j+^7q[x]+'`Px);c++}`2^Wk,v,0)`Awdl`7'e`G`Ks=`9,r=@p,b=^X(`F,\"^v\"),i,o,oc`5b)r=^S$f^Bi=0;i<s.d.`Ns`C@A{o=s.d.`Ns[i];oc=o.`k?\"\"+o.`k:\"\"`5(oc`4$"
+"B<0||oc`4\"@0oc(\")>=0)&&oc`4$W<0)^X(o,\"`k\",0,s.lc);}`2r^R`Fs`0`1`5`O>3^m!^Y$es.^f||`O#E`Hs.b^E$D^Q)s.$D^Q('`k',s.bc);`Bs.b^Eb.add^Q$A)s.b.add^Q$A('clic$a,false);`m^X(`F,'^v',0,`Fl)}`Avs`0x`1,v=s"
+".`c^N,g=s.`c^N#5k=@Nvsn^n^C+(g?'^ng`j,n=^Vk),e`Z,y=e.g@K);e.s@Ky+10@l1900:0))`5v){v*=100`5!n`H!^Wk,x,e))`20;n=x`ln%10000>v)`20}`21`Adyasmf`0t,m`H#Am&&m`4t)>=0)`21;`20`Adyasf`0t,m`1,i=t?t`4@e:-1,n,x"
+"`5i>=0&&m){`Kn=t`30,i),x=t`3i+1)`5`Lx,`G,'dyasm^um))`2n}`20`Auns`0`1,x=s.`MSele@6,l=s.`MList,m=s.`MM$s,n,i;^C=^C`8`5x&&l`H!m)m=`F`J^5`5!m.toLowerCase)m`e+m;l=l`8;m=m`8;n=`Ll,';`Gdyas^um)`5n)^C=n}i="
+"^C`4`G`Rfun=i<0?^C:^C`30,i)`Asa`0un`1;^C=un`5!@S)@S=un;`B(`G+@S+`G)`4$S<0)@S+=`G+un;^Cs()`Am_i`0n,a`1,m,f=n`30,1),r,l,i`5!`Wl)`Wl`E`5!`Wnl)`Wnl`U;m=`Wl[n]`5!a&&m&&m._e@Lm^s)`Wa(n)`5!m){m`E,m._c=@Nm"
+"';m^sn=`F`hn;m^sl=s^sl;m^sl[m^s@om;`F`hn++;m.s=s;m._n=n;m._l`U('_c`G_in`G_il`G_i`G_e`G_d`G_dl`Gs`Gn`G_r`G_g`G_g1`G_t`G_t1`G_x`G_x1`G_l'`Rm_l[@om;`Wnl[`Wnl`C]=n}`Bm._r@Lm._m){r=m._r;r._m=m;l=m._l;^B"
+"i=0;i<l`C@A@tm[l[i]])r[l[i]]=m[l[i]];r^sl[r^s@or;m=`Wl[@or`lf==f`D())s[@om;`2m`Am_a`7'n`Gg`G@t!g)g=#2;`Ks=`9,c=s[$V,m,x,f=0`5!c)c=`F$u$V`5c&&s_d)s[g]`7\"s\",s_ft(s_d(c)));x=s[g]`5!x)x=`F$ug];m=`Wi("
+"n,1)`5x){m^s=f=1`5(\"\"+x)`4\"fun@6\")>=0)x(s);`m`Wm(\"x\",n,x)}m=`Wi(n,1)`5@Zl)@Zl=@Z=0;`pt();`2f'`Rm_m`0t,n,d){t='^nt;`Ks=^S,i,x,m,f='^nt`5`Wl&&`Wnl)^Bi=0;i<`Wnl`C@A{x=`Wnl[i]`5!n||x==n){m=`Wi(x)"
+"`5m[t]`Ht`t_d')`21`5d)m#Fd);`mm#F)`lm[t+1]@Lm[f]`Hd)$gd);`m$g)}m[f]=1}}`20`AloadModule`0n,u,d,l`1,m,i=n`4':'),g=i<0?#2:n`3i+1),o=0,f,c=s.h?s.h:s.b,^d`5i>=0)n=n`30,i);m=`Wi(n)`5(l$e`Wa(n,g))&&u^Ed&&"
+"c^E$E`S`Hd){@Z=1;@Zl=1`l@3)u=`vu,@u:`Ghttps:^Rf`7'e`G`9.m_a(\"$J+'\",\"'+g+'\")^R^d`7's`Gf`Gu`Gc`G`Ke,o=0@Oo=s.$E`S(\"script\")`5o){@4=\"text/`o\"`5f)o.^v=f;o@I=u;c.appendChild(o)}`bo=0}`2o^Ro=^d(s"
+",f,u,c)}`mm=`Wi(n);m._e=1;`2m`Avo1`0t,a`Ha[t]||$P)^S#Da[t]`Avo2`0t,a`H#H{a#D^S[t]`5#H$P=1}`Adlt`7'`Ks=`9,d`Z,i,vo,f=0`5`pl)^Bi=0;i<`pl`C@A{vo=`pl[i]`5vo`H!`Wm(\"d\")||d`T-$C>=^8){`pl[i]=0;s.t(@i}`m"
+"f=1}`l`pi)clear@5`pi`Rdli=0`5f`H!`pi)`pi=set@5`pt,^8)}`m`pl=0'`Rdl`0vo`1,d`Z`5!@ivo`E;`L^9,`G$72',@i;$C=d`T`5!`pl)`pl`U;`pl[`pl`C]=vo`5!^8)^8=250;`pt()`At`0vo,id`1,trk=1,tm`Z,sed=Math&&@P$l?@P$r@P$"
+"l()*10000000000000):tm`T,@q='s'+@P$rtm`T/10800000)%10+sed,y=tm.g@K),vt=tm.getDate(@f`sMonth(@f'@ly+1900:y)+' `sHour$K:`sMinute$K:`sSecond$K `sDay()+' `sTimezoneO@z(),^d,^T=s.g^T(),ta`e,q`e,qs`e,$m`"
+"e,vb`E#1^9`Runs()`5!s.td){`Ktl=^T`J,a,o,i,x`e,c`e,v`e,p`e,bw`e,bh`e,^H0',k=^W@Ncc`G@p',0^q,hp`e,ct`e,pn=0,ps`5^3&&^3.prototype){^H1'`5j.m$s){^H2'`5tm.setUTCDate){^H3'`5^Y^E^f&&`O#E^H4'`5pn.toPrecis"
+"ion){^H5';a`U`5a.forEach){^H6';i=0;o`E;^d`7'o`G`Ke,i=0@Oi=new Iterator(o)`b}`2i^Ri=^d(o)`5i&&i.next)^H7'}}}}`l`O>=4)x=^iwidth+'x'+^i$j`5s.isns||s.^e`H`O>=3$Q`f(^q`5`O>=4){c=^ipixelDepth;bw=`F$z@2;b"
+"h=`F$z^b}}$8=s.n.p^J}`B^Y`H`O>=4$Q`f(^q;c=^i^2`5`O#E{bw=s.d.^L`S.o@z@2;bh=s.d.^L`S.o@z^b`5!s.^f^Eb){^d`7's`Gtl`G`Ke,hp=0`qh$b\");hp=s.b.isH$b(tl)?\"Y\":\"N\"`b}`2hp^Rhp=^d(s,tl);^d`7's`G`Ke,ct=0`qc"
+"lientCaps\");ct=s.b.`g`b}`2ct^Rct=^d(s)}}}`mr`e`l$8)^4pn<$8`C&&pn<30){ps=^j$8[pn].^w@v#9`5p`4ps)<0)p+=ps;pn++}s.^U=x;s.^2=c;s.`o^k=j;s.`f=v;s.`u@9=k;s.`z@2=bw;s.`z^b=bh;s.`g=ct;s.^x=hp;s.p^J=p;s.td"
+"=1`l@i{`L^9,`G$72',vb);`L^9,`G$71',@i`ls.useP^J)s.doP^J(s);`Kl=`F`J,r=^T.^L.`X`5!s.^I)s.^I=l^h?l^h:l`5!s.`X@Ls._1_`X#C`X=r;s._1_`X=1}`Wm('g')`5(vo&&$C)$e`Wm('d')`Hs.@G||^D){`Ko=^D?^D:s.@G`5!o)`2'';"
+"`Kp=$4'#4`i'),w=1,^G,@a,x=`yt,h,l,i,oc`5^D&&o==^D){^4o@Ln@W$HBODY'){o=o^0`S?o^0`S:o^0Node`5!o)`2'';^G;@a;x=`yt}oc=o.`k?''+o.`k:''`5(oc`4$B>=0&&oc`4\"@0oc(\")<0)||oc`4$W>=0)`2''}ta=n?o$T:1;h@ki=h`4'"
+"?^Rh=s.`N@c^3||i<0?h:h`30,i);l=s.`N`i?s.`N`i:s.ln(h);t=s.`N^M?s.`N^M`8:s.lt(h)`5t^mh||l))q+=$2=@G^n(t`td$I`te'?@y(t):'o')+(h?$2v1`Ph)`j+(l?$2v2`Pl)`j;`mtrk=0`5s.`x@T`H!p$L$4'^I^Rw=0}^G;i=o.sourceIn"
+"dex`5$3'^y')@g$3'^y^Rx=1;i=1`lp&&n@W)qs='&pid`P^jp,255))+(w#8p#3w`j+'&oid`P^jn@v)+(x#8o#3x`j+'&ot`Pt)+(i#8oi='+i`j}`l!trk@Lqs)`2'';@j=s.vs(sed)`5trk`H@j)$m=s.mr(@q,(vt#8t`Pvt)`j+s.hav()+q+(qs?qs:s."
+"rq(^C)),0,id,ta);qs`e;`Wm('t')`5s.p_r)s.p_r(`R`X`e}^7(qs);^z`p(@i;`l@i`L^9,`G$71',vb`R@G=^D=s.`N`i=s.`N^M=`F@0^y=s.ppu=^p=^pv1=^pv2=^pv3`e`5$x)`F@0@G=`F@0eo=`F@0`N`i=`F@0`N^M`e`5!id@Ls.tc#Ctc=1;s.f"
+"lush`a()}`2$m`Atl`0o,t,n,vo`1;s.@G=@wo`R`N^M=t;s.`N`i=n;s.t(@i}`5pg){`F@0co`0o){`K@J\"_\",1,#B`2@wo)`Awd@0gs`0$S{`K@J$p1,#B`2s.t()`Awd@0dc`0$S{`K@J$p#B`2s.t()}}@3=(`F`J`Y`8`4@us@d0`Rd=^L;s.b=s.d.bo"
+"dy`5$c`S#7`i#Ch=$c`S#7`i('HEAD')`5s.h)s.h=s.h[0]}s.n=navigator;s.u=s.n.userAgent;@R=s.u`4'N$X6/^R`Kapn$F`i,v$F^k,ie=v`4$n'),o=s.u`4'@M '),i`5v`4'@M@d0||o>0)apn='@M';^Y$9`tMicrosoft Internet Explore"
+"r'`Risns$9`tN$X'`R^e$9`t@M'`R^f=(s.u`4'Mac@d0)`5o>0)`O`rs.u`3o+6));`Bie>0){`O=^Fi=v`3ie+5))`5`O>3)`O`ri)}`B@R>0)`O`rs.u`3@R+10));`m`O`rv`Rem=0`5^3#6^l){i=^g^3#6^l(256))`D(`Rem=(i`t%C4%80'?2:(i`t%U0"
+"100'?1:0))}s.sa(un`Rvl_l='^K,`cID,vmk,ppu,@E,`c`ispace,c`V,`u@7,#4`i,^I,`X,@H';^a=^Z+',^o,$R,server,#4^M,#0@6ID,purchaseID,@r,state,zip,$k,products,`N`i,`N^M';^B`Kn=1;n<51;n++)^a+=',prop$J+',eVar$J"
+"+',hier$J;^Z2=',^U,^2,`o^k,`f,`u@9,`z@2,`z^b,`g,^x,pe$q1$q2$q3,p^J';^a+=^Z2;^9=^a+',$i,`c^N,`c^N#5`MSele@6,`MList,`MM$s,`x^PLinks,`x@D,`x@T,`N@c^3,`N^PFile^Ms,`NEx`n,`NIn`n,`N@UVa$o`N@U^Qs,`N`is,@G"
+",eo';$x=pg#1^9)`5!ss)`Fs()",
w=window,l=w.s_c_il,n=navigator,u=n.userAgent,v=n.appVersion,e=v.indexOf('MSIE '),m=u.indexOf('Netscape6/'),a,i,s;if(un){un=un.toLowerCase();if(l)for(i=0;i<l.length;i++){s=l[i];if(s._c=='s_c'){if(s.oun==un)return s;else if(s.fs&&s.sa&&s.fs(s.oun,un)){s.sa(un);return s;}}}}
w.s_r=new Function("x","o","n","var i=x.indexOf(o);if(i>=0&&x.split)x=(x.split(o)).join(n);else while(i>=0){x=x.substring(0,i)+n+x.substring(i+o.length);i=x.indexOf(o)}return x");
w.s_d=new Function("x","var t='`^@$#',l='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',d,n=0,b,k,w,i=x.lastIndexOf('~~');if(i>0){d=x.substring(0,i);x=x.substring(i+2);while(d){w=d;i"
+"=d.indexOf('~');if(i>0){w=d.substring(0,i);d=d.substring(i+1)}else d='';b=(n-n%62)/62;k=n-b*62;k=t.substring(b,b+1)+l.substring(k,k+1);x=s_r(x,k,w);n++}for(i=0;i<5;i++){w=t.substring(i,i+1);x=s_r(x"
+",w+' ',w)}}return x");
w.s_fe=new Function("c","return s_r(s_r(s_r(c,'\\\\','\\\\\\\\'),'\"','\\\\\"'),\"\\n\",\"\\\\n\")");
w.s_fa=new Function("f","var s=f.indexOf('(')+1,e=f.indexOf(')'),a='',c;while(s>=0&&s<e){c=f.substring(s,s+1);if(c==',')a+='\",\"';else if((\"\\n\\r\\t \").indexOf(c)<0)a+=c;s++}return a?'\"'+a+'\"':"
+"a");
w.s_ft=new Function("c","c+='';var s,e,o,a,d,q,f,h,x;s=c.indexOf('=function(');while(s>=0){s++;d=1;q='';x=0;f=c.substring(s);a=s_fa(f);e=o=c.indexOf('{',s);e++;while(d>0){h=c.substring(e,e+1);if(q){i"
+"f(h==q&&!x)q='';if(h=='\\\\')x=x?0:1;else x=0}else{if(h=='\"'||h==\"'\")q=h;if(h=='{')d++;if(h=='}')d--}if(d>0)e++}c=c.substring(0,s)+'new Function('+(a?a+',':'')+'\"'+s_fe(c.substring(o+1,e))+'\")"
+"'+c.substring(e+1);s=c.indexOf('=function(')}return c;");
c=s_d(c);if(e>0){a=parseInt(i=v.substring(e+5));if(a>3)a=parseFloat(i);}else if(m>0)a=parseFloat(u.substring(m+10));else a=parseFloat(v);if(a>=5&&v.indexOf('Opera')<0&&u.indexOf('Opera')<0){w.s_c=new Function("un","pg","ss","var s=this;"+c);return new s_c(un,pg,ss);}else s=new Function("un","pg","ss","var s=new Object;"+s_ft(c)+";return s");return s(un,pg,ss);}


var Gilt;
if (!Gilt) Gilt = { };

Gilt.Omniture = { };

Gilt.Omniture.buildSCode = function(s, data) {
  $.extend(s, data);

  var user_identifier = fl.Util.readUserId();
  if (user_identifier == null || user_identifier == "") {
    user_identifier = fl.Util.readHashedCookie("guid");
  }

  // Link tracking cid
  s.campaign = s.getCookieParam('cid');

  /* set tracking data for cached pages from the zeus ifs URL param */
  var ifs = document.location.search.match(/\bifs=([^&]*)?/);
  if (ifs) {
    ifs = decodeURIComponent(ifs[1]);
    var mailing_id = ifs.match(/\bmailing_id=([^&]*)?/);
    if (mailing_id) {
      s.campaign = mailing_id[1];
    }
    var link_type = ifs.match(/\blink_type=([^&]*)?/);
    if (link_type) {
      s.eVar2 = s.campaign + ' ' + link_type[1] + ' ' + s.pageName;
      s.prop3 = s.eVar2;
    }
  }

  /* fire the registration event only if we have the registration cookie and are not on the registration page */
  if(document.cookie.match('t_register') && !document.location.pathname.match(/^\/(account\/register|bb\/register|invite\/.*)$/)){
    s.events = s.events + ',event4';
  }
  
  /* Set User ID from the user id or guid cookie */
  s.prop6 = user_identifier;
  s.eVar12 = s.prop6;
  return s.t();
};

Gilt.Omniture.homepageLinks = {
    'meta': 'div#carousel-nav-top-bar a',
    'nav':  'div#carousel-nav-bottom-bar a',
    'hero': 'a#promos',
    'inv':  '#sales > div.mosaic_promotion a',
    'cal':  'a#calendar_invite',
    'list': '#sales > div.also_like ul.links li a',
    'edit': '#sales > div.editors_pick ul.links li a'
}

Gilt.Omniture.registerLinks = function() {
    for(var name in Gilt.Omniture.homepageLinks) { 
        var selector = Gilt.Omniture.homepageLinks[name]; 
        $(selector).data('slug', name).click(function() {
            var name = $(this).data('slug');

            // Heroes are manually tagged, so pull out the unique string from the link's url
            var extra = "";
            if(name == "hero") {
                var heroUrl = $(this).attr('href');
                extra = "-" + jQuery.url.setUrl(heroUrl).param("cid");
            }

            var campaign = "" + Gilt.Omniture.cid() + name + extra;
            fl.Util.setSessionCookie('cid', campaign);
        });
    }
}

Gilt.Omniture.cid = function() {
    var subsite = identify_domain_name(document.location.host);
    if(subsite) {
        var subsiteInitial = subsite[0];
    }

    if(subsite == "man" || subsite == "fuse")
        return subsiteInitial

    var categoryInitial = '';
    var categoryMatch = document.location.pathname.match(/^\/sale\/([^\/\?]+)/)
    if(categoryMatch && categoryMatch.length == 2) {
        categoryInitial = categoryMatch[1][0];
    } else {
        var category = $('#carousel-nav-links-left li.selected').id();
        if(category) {
            categoryInitial = category.replace(/category-/, '')[0];
        }
    }

    return "" + subsiteInitial + categoryInitial;
}

// Call on page load
$(function() { 
  Gilt.Omniture.registerLinks(); 
});


var Gilt;
if (!Gilt) {
  Gilt = { };
}
Gilt.Atlas = { };

Gilt.Atlas.enabled = true;

Gilt.Atlas.disable = function() {
  Gilt.Atlas.enabled = false;
};

Gilt.Atlas.buildExtendedUrl = function(action_name, data) {
  var url = document.location.protocol + "//view.atdmt.com/jaction/" + action_name + "/v3";
  $.each(data, function(k,v) {
    url += '/' + k + '.' + v;
  });
  return url;
};

Gilt.Atlas.requestJavaScript = function(url) {
  if (!Gilt.Atlas.enabled) {
    return;
  }
  $(function() {
    try {
      $.getScript(url);
    } catch (err) {
      Gilt.Atlas.notifyError(err);
    }
  });
};

// Request any resource which is not Javascript, such as an image.
Gilt.Atlas.requestResource = function(url) {
  if (!Gilt.Atlas.enabled) {
    return;
  }
  $(function() {
    try {
      var i = new Image();
      i.src = url;
      document.appendChild(i);
    } catch (err) {
      Gilt.Atlas.notifyError(err);
    }
  });
};

Gilt.Atlas.tagNameForSubsite = function(subsiteKey) {
	return subsiteKey == 'us' ? 'gilt' : subsiteKey;
};

Gilt.Atlas.notifyError = function(err) {
  // TODO: notify
};


var Gilt;
if (!Gilt) {
  Gilt = { };
}

Gilt.Discount = { };

/* Discounts available for a particular subtotal.
   Requires that Gilt.Discount.discounts is set. */
Gilt.Discount.available = function(subtotal) {
  var discounts = Gilt.Discount.discounts;
  var available = [];
  if (discounts) {
    for(var i = 0; i < discounts.length; ++i) {
      var discount = discounts[i];
      // Add missing pretty_description
      if (!discount.pretty_description) {
        discount.pretty_description = Gilt.Discount.prettyDescription(discount);
      }
      if (discount.price_threshold) {
        if (subtotal >= discount.price_threshold) {
          available.push(discount);
        }
      } else if ("ReturnRefundDiscount" == discount.type) {
        if (gg.Cart.hasReturnableItems()) {
          available.push(discount);
        }
      } else {
        available.push(discount);
      }
    }
  }
  return available;
};

Gilt.Discount.showDiscountDetails = function(discountId) {
  $(".discount_info").hide();
  $("#discount_info_" + discountId).show();
};

Gilt.Discount.showDiscountTerms = function() {
  var discount_id = $('[name=discount]').fieldValue()[0]; // is this an input? textarea? select? [] is extremely inefficient
  $("#discount_terms div").hide();
  $("#discount_terms #discount_" + discount_id).show();
  fl.Util.getDialog("discount_terms", {
    title: "Terms and Conditions of Discount",
    height: 348,
    width: 458
  }).dialog("open");
};

/* Append <p> tags to #discount_list if available */
Gilt.Discount.drawAvailable = function(subtotal) {
  var available = Gilt.Discount.available(subtotal);
  if (available.length) {
    if ($("td.flashMessage").text().replace(/\s/g, '').length) {
      $("td.flashMessage").append("<br/>");
    }
    $("td.flashMessage").append("This order is eligible for a special offer (see details below)");
    $('#discount_list')
      .append('<span class="brand">Eligible Offers:</span>')
      .append('<ul>');
    for(var i = 0; i < available.length; ++i) {
      $('#discount_list ul').append('<li class="reservation_time">' + available[i].pretty_description + "</li>");
    }
    $('#discount_list').append('</ul>');
  }
};

/* Construct a pretty description (normally done in Rails) */
Gilt.Discount.prettyDescription = function(discount) {
  var description = '';
  if (discount.type == 'FreeShippingDiscount') {
    if (discount.price_threshold) {
      description = 'Free ground shipping on orders of $' + discount.price_threshold + '.00 or more';
    } else {
      description = 'Free ground shipping';
    }
  } else if (discount.type == "DollarOffDiscount") {
    if (discount.price_threshold) {
      description = '$' + discount.amount + '.00 off on orders of $' + discount.price_threshold + '.00 or more';
    } else {
      description = '$' + discount.amount + '.00 off';
    }
  } else if (discount.type == "PercentOffDiscount") {
    if (discount.price_threshold) {
      description = discount.percent + '% off on orders of $' + discount.price_threshold + '.00 or more';
    } else {
      description = discount.percent + '% off';
    }
  } else if (discount.type == 'ReturnRefundDiscount') {
    description = 'Full refund if you return this order';
  }
  return description;
};

/**
* DD_belatedPNG: Adds IE6 support: PNG images for CSS background-image and HTML <IMG/>.
* Author: Drew Diller
* Email: drew.diller@gmail.com
* URL: http://www.dillerdesign.com/experiment/DD_belatedPNG/
* Version: 0.0.8a
* Licensed under the MIT License: http://dillerdesign.com/experiment/DD_belatedPNG/#license
*
* Example usage:
* DD_belatedPNG.fix('.png_bg'); // argument is a CSS selector
* DD_belatedPNG.fixPng( someNode ); // argument is an HTMLDomElement
**/
try { // Needed for IE6, but blows up in IE8.  Figures
  var DD_belatedPNG={ns:"DD_belatedPNG",imgSize:{},delay:10,nodesFixed:0,createVmlNameSpace:function(){if(document.namespaces&&!document.namespaces[this.ns]){document.namespaces.add(this.ns,"urn:schemas-microsoft-com:vml")}},createVmlStyleSheet:function(){var b,a;b=document.createElement("style");b.setAttribute("media","screen");document.documentElement.firstChild.insertBefore(b,document.documentElement.firstChild.firstChild);if(b.styleSheet){b=b.styleSheet;b.addRule(this.ns+"\\:*","{behavior:url(#default#VML)}");b.addRule(this.ns+"\\:shape","position:absolute;");b.addRule("img."+this.ns+"_sizeFinder","behavior:none; border:none; position:absolute; z-index:-1; top:-10000px; visibility:hidden;");this.screenStyleSheet=b;a=document.createElement("style");a.setAttribute("media","print");document.documentElement.firstChild.insertBefore(a,document.documentElement.firstChild.firstChild);a=a.styleSheet;a.addRule(this.ns+"\\:*","{display: none !important;}");a.addRule("img."+this.ns+"_sizeFinder","{display: none !important;}")}},readPropertyChange:function(){var b,c,a;b=event.srcElement;if(!b.vmlInitiated){return}if(event.propertyName.search("background")!=-1||event.propertyName.search("border")!=-1){DD_belatedPNG.applyVML(b)}if(event.propertyName=="style.display"){c=(b.currentStyle.display=="none")?"none":"block";for(a in b.vml){if(b.vml.hasOwnProperty(a)){b.vml[a].shape.style.display=c}}}if(event.propertyName.search("filter")!=-1){DD_belatedPNG.vmlOpacity(b)}},vmlOpacity:function(b){if(b.currentStyle.filter.search("lpha")!=-1){var a=b.currentStyle.filter;a=parseInt(a.substring(a.lastIndexOf("=")+1,a.lastIndexOf(")")),10)/100;b.vml.color.shape.style.filter=b.currentStyle.filter;b.vml.image.fill.opacity=a}},handlePseudoHover:function(a){setTimeout(function(){DD_belatedPNG.applyVML(a)},1)},fix:function(a){if(this.screenStyleSheet){var c,b;c=a.split(",");for(b=0;b<c.length;b++){this.screenStyleSheet.addRule(c[b],"behavior:expression(DD_belatedPNG.fixPng(this))")}}},applyVML:function(a){a.runtimeStyle.cssText="";this.vmlFill(a);this.vmlOffsets(a);this.vmlOpacity(a);if(a.isImg){this.copyImageBorders(a)}},attachHandlers:function(i){var d,c,g,e,b,f;d=this;c={resize:"vmlOffsets",move:"vmlOffsets"};if(i.nodeName=="A"){e={mouseleave:"handlePseudoHover",mouseenter:"handlePseudoHover",focus:"handlePseudoHover",blur:"handlePseudoHover"};for(b in e){if(e.hasOwnProperty(b)){c[b]=e[b]}}}for(f in c){if(c.hasOwnProperty(f)){g=function(){d[c[f]](i)};i.attachEvent("on"+f,g)}}i.attachEvent("onpropertychange",this.readPropertyChange)},giveLayout:function(a){a.style.zoom=1;if(a.currentStyle.position=="static"){a.style.position="relative"}},copyImageBorders:function(b){var c,a;c={borderStyle:true,borderWidth:true,borderColor:true};for(a in c){if(c.hasOwnProperty(a)){b.vml.color.shape.style[a]=b.currentStyle[a]}}},vmlFill:function(e){if(!e.currentStyle){return}else{var d,f,g,b,a,c;d=e.currentStyle}for(b in e.vml){if(e.vml.hasOwnProperty(b)){e.vml[b].shape.style.zIndex=d.zIndex}}e.runtimeStyle.backgroundColor="";e.runtimeStyle.backgroundImage="";f=true;if(d.backgroundImage!="none"||e.isImg){if(!e.isImg){e.vmlBg=d.backgroundImage;e.vmlBg=e.vmlBg.substr(5,e.vmlBg.lastIndexOf('")')-5)}else{e.vmlBg=e.src}g=this;if(!g.imgSize[e.vmlBg]){a=document.createElement("img");g.imgSize[e.vmlBg]=a;a.className=g.ns+"_sizeFinder";a.runtimeStyle.cssText="behavior:none; position:absolute; left:-10000px; top:-10000px; border:none; margin:0; padding:0;";c=function(){this.width=this.offsetWidth;this.height=this.offsetHeight;g.vmlOffsets(e)};a.attachEvent("onload",c);a.src=e.vmlBg;a.removeAttribute("width");a.removeAttribute("height");document.body.insertBefore(a,document.body.firstChild)}e.vml.image.fill.src=e.vmlBg;f=false}e.vml.image.fill.on=!f;e.vml.image.fill.color="none";e.vml.color.shape.style.backgroundColor=d.backgroundColor;e.runtimeStyle.backgroundImage="none";e.runtimeStyle.backgroundColor="transparent"},vmlOffsets:function(d){var h,n,a,e,g,m,f,l,j,i,k;h=d.currentStyle;n={W:d.clientWidth+1,H:d.clientHeight+1,w:this.imgSize[d.vmlBg].width,h:this.imgSize[d.vmlBg].height,L:d.offsetLeft,T:d.offsetTop,bLW:d.clientLeft,bTW:d.clientTop};a=(n.L+n.bLW==1)?1:0;e=function(b,p,q,c,s,u){b.coordsize=c+","+s;b.coordorigin=u+","+u;b.path="m0,0l"+c+",0l"+c+","+s+"l0,"+s+" xe";b.style.width=c+"px";b.style.height=s+"px";b.style.left=p+"px";b.style.top=q+"px"};e(d.vml.color.shape,(n.L+(d.isImg?0:n.bLW)),(n.T+(d.isImg?0:n.bTW)),(n.W-1),(n.H-1),0);e(d.vml.image.shape,(n.L+n.bLW),(n.T+n.bTW),(n.W),(n.H),1);g={X:0,Y:0};if(d.isImg){g.X=parseInt(h.paddingLeft,10)+1;g.Y=parseInt(h.paddingTop,10)+1}else{for(j in g){if(g.hasOwnProperty(j)){this.figurePercentage(g,n,j,h["backgroundPosition"+j])}}}d.vml.image.fill.position=(g.X/n.W)+","+(g.Y/n.H);m=h.backgroundRepeat;f={T:1,R:n.W+a,B:n.H,L:1+a};l={X:{b1:"L",b2:"R",d:"W"},Y:{b1:"T",b2:"B",d:"H"}};if(m!="repeat"||d.isImg){i={T:(g.Y),R:(g.X+n.w),B:(g.Y+n.h),L:(g.X)};if(m.search("repeat-")!=-1){k=m.split("repeat-")[1].toUpperCase();i[l[k].b1]=1;i[l[k].b2]=n[l[k].d]}if(i.B>n.H){i.B=n.H}d.vml.image.shape.style.clip="rect("+i.T+"px "+(i.R+a)+"px "+i.B+"px "+(i.L+a)+"px)"}else{d.vml.image.shape.style.clip="rect("+f.T+"px "+f.R+"px "+f.B+"px "+f.L+"px)"}},figurePercentage:function(d,c,f,a){var b,e;e=true;b=(f=="X");switch(a){case"left":case"top":d[f]=0;break;case"center":d[f]=0.5;break;case"right":case"bottom":d[f]=1;break;default:if(a.search("%")!=-1){d[f]=parseInt(a,10)/100}else{e=false}}d[f]=Math.ceil(e?((c[b?"W":"H"]*d[f])-(c[b?"w":"h"]*d[f])):parseInt(a,10));if(d[f]%2===0){d[f]++}return d[f]},fixPng:function(c){c.style.behavior="none";var g,b,f,a,d;if(c.nodeName=="BODY"||c.nodeName=="TD"||c.nodeName=="TR"){return}c.isImg=false;if(c.nodeName=="IMG"){if(c.src.toLowerCase().search(/\.png$/)!=-1){c.isImg=true;c.style.visibility="hidden"}else{return}}else{if(c.currentStyle.backgroundImage.toLowerCase().search(".png")==-1){return}}g=DD_belatedPNG;c.vml={color:{},image:{}};b={shape:{},fill:{}};for(a in c.vml){if(c.vml.hasOwnProperty(a)){for(d in b){if(b.hasOwnProperty(d)){f=g.ns+":"+d;c.vml[a][d]=document.createElement(f)}}c.vml[a].shape.stroked=false;c.vml[a].shape.appendChild(c.vml[a].fill);c.parentNode.insertBefore(c.vml[a].shape,c)}}c.vml.image.shape.fillcolor="none";c.vml.image.fill.type="tile";c.vml.color.fill.on=false;g.attachHandlers(c);g.giveLayout(c);g.giveLayout(c.offsetParent);c.vmlInitiated=true;g.applyVML(c)}};try{document.execCommand("BackgroundImageCache",false,true)}catch(r){}DD_belatedPNG.createVmlNameSpace();DD_belatedPNG.createVmlStyleSheet();
} catch(_) {}
(function() {
  var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var b64pad="=";

  function hex2b64(h) {
    var i;
    var c;
    var ret = "";
    for(i = 0; i+3 <= h.length; i+=3) {
      c = parseInt(h.substring(i,i+3),16);
      ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
    }
    if(i+1 == h.length) {
      c = parseInt(h.substring(i,i+1),16);
      ret += b64map.charAt(c << 2);
    }
    else if(i+2 == h.length) {
      c = parseInt(h.substring(i,i+2),16);
      ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
    }
    while((ret.length & 3) > 0) ret += b64pad;
    return ret;
  }

// convert a base64 string to hex
  function b64tohex(s) {
    var ret = ""
    var i;
    var k = 0; // b64 state, 0-3
    var slop;
    for(i = 0; i < s.length; ++i) {
      if(s.charAt(i) == b64pad) break;
      v = b64map.indexOf(s.charAt(i));
      if(v < 0) continue;
      if(k == 0) {
        ret += int2char(v >> 2);
        slop = v & 3;
        k = 1;
      }
      else if(k == 1) {
        ret += int2char((slop << 2) | (v >> 4));
        slop = v & 0xf;
        k = 2;
      }
      else if(k == 2) {
        ret += int2char(slop);
        ret += int2char(v >> 2);
        slop = v & 3;
        k = 3;
      }
      else {
        ret += int2char((slop << 2) | (v >> 4));
        ret += int2char(v & 0xf);
        k = 0;
      }
    }
    if(k == 1)
      ret += int2char(slop << 2);
    return ret;
  }

// convert a base64 string to a byte/number array
  function b64toBA(s) {
    //piggyback on b64tohex for now, optimize later
    var h = b64tohex(s);
    var i;
    var a = new Array();
    for(i = 0; 2*i < h.length; ++i) {
      a[i] = parseInt(h.substring(2*i,2*i+2),16);
    }
    return a;
  }
// Copyright (c) 2005  Tom Wu
// All Rights Reserved.
// See "LICENSE" for details.

// Basic JavaScript BN library - subset useful for RSA encryption.

// Bits per digit
  var dbits;

// JavaScript engine analysis
  var canary = 0xdeadbeefcafe;
  var j_lm = ((canary&0xffffff)==0xefcafe);

// (public) Constructor
  function BigInteger(a,b,c) {
    if(a != null)
      if("number" == typeof a) this.fromNumber(a,b,c);
      else if(b == null && "string" != typeof a) this.fromString(a,256);
      else this.fromString(a,b);
  }

// return new, unset BigInteger
  function nbi() { return new BigInteger(null); }

// am: Compute w_j += (x*this_i), propagate carries,
// c is initial carry, returns final carry.
// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
// We need to select the fastest one that works in this environment.

// am1: use a single mult and divide to get the high bits,
// max digit bits should be 26 because
// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
  function am1(i,x,w,j,c,n) {
    while(--n >= 0) {
      var v = x*this[i++]+w[j]+c;
      c = Math.floor(v/0x4000000);
      w[j++] = v&0x3ffffff;
    }
    return c;
  }
// am2 avoids a big mult-and-extract completely.
// Max digit bits should be <= 30 because we do bitwise ops
// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
  function am2(i,x,w,j,c,n) {
    var xl = x&0x7fff, xh = x>>15;
    while(--n >= 0) {
      var l = this[i]&0x7fff;
      var h = this[i++]>>15;
      var m = xh*l+h*xl;
      l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);
      c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
      w[j++] = l&0x3fffffff;
    }
    return c;
  }
// Alternately, set max digit bits to 28 since some
// browsers slow down when dealing with 32-bit numbers.
  function am3(i,x,w,j,c,n) {
    var xl = x&0x3fff, xh = x>>14;
    while(--n >= 0) {
      var l = this[i]&0x3fff;
      var h = this[i++]>>14;
      var m = xh*l+h*xl;
      l = xl*l+((m&0x3fff)<<14)+w[j]+c;
      c = (l>>28)+(m>>14)+xh*h;
      w[j++] = l&0xfffffff;
    }
    return c;
  }
  if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
    BigInteger.prototype.am = am2;
    dbits = 30;
  }
  else if(j_lm && (navigator.appName != "Netscape")) {
    BigInteger.prototype.am = am1;
    dbits = 26;
  }
  else { // Mozilla/Netscape seems to prefer am3
    BigInteger.prototype.am = am3;
    dbits = 28;
  }

  BigInteger.prototype.DB = dbits;
  BigInteger.prototype.DM = ((1<<dbits)-1);
  BigInteger.prototype.DV = (1<<dbits);

  var BI_FP = 52;
  BigInteger.prototype.FV = Math.pow(2,BI_FP);
  BigInteger.prototype.F1 = BI_FP-dbits;
  BigInteger.prototype.F2 = 2*dbits-BI_FP;

// Digit conversions
  var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
  var BI_RC = new Array();
  var rr,vv;
  rr = "0".charCodeAt(0);
  for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
  rr = "a".charCodeAt(0);
  for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
  rr = "A".charCodeAt(0);
  for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;

  function int2char(n) { return BI_RM.charAt(n); }
  function intAt(s,i) {
    var c = BI_RC[s.charCodeAt(i)];
    return (c==null)?-1:c;
  }

// (protected) copy this to r
  function bnpCopyTo(r) {
    for(var i = this.t-1; i >= 0; --i) r[i] = this[i];
    r.t = this.t;
    r.s = this.s;
  }

// (protected) set from integer value x, -DV <= x < DV
  function bnpFromInt(x) {
    this.t = 1;
    this.s = (x<0)?-1:0;
    if(x > 0) this[0] = x;
    else if(x < -1) this[0] = x+DV;
    else this.t = 0;
  }

// return bigint initialized to value
  function nbv(i) { var r = nbi(); r.fromInt(i); return r; }

// (protected) set from string and radix
  function bnpFromString(s,b) {
    var k;
    if(b == 16) k = 4;
    else if(b == 8) k = 3;
    else if(b == 256) k = 8; // byte array
    else if(b == 2) k = 1;
    else if(b == 32) k = 5;
    else if(b == 4) k = 2;
    else { this.fromRadix(s,b); return; }
    this.t = 0;
    this.s = 0;
    var i = s.length, mi = false, sh = 0;
    while(--i >= 0) {
      var x = (k==8)?s[i]&0xff:intAt(s,i);
      if(x < 0) {
        if(s.charAt(i) == "-") mi = true;
        continue;
      }
      mi = false;
      if(sh == 0)
        this[this.t++] = x;
      else if(sh+k > this.DB) {
        this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh;
        this[this.t++] = (x>>(this.DB-sh));
      }
      else
        this[this.t-1] |= x<<sh;
      sh += k;
      if(sh >= this.DB) sh -= this.DB;
    }
    if(k == 8 && (s[0]&0x80) != 0) {
      this.s = -1;
      if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh;
    }
    this.clamp();
    if(mi) BigInteger.ZERO.subTo(this,this);
  }

// (protected) clamp off excess high words
  function bnpClamp() {
    var c = this.s&this.DM;
    while(this.t > 0 && this[this.t-1] == c) --this.t;
  }

// (public) return string representation in given radix
  function bnToString(b) {
    if(this.s < 0) return "-"+this.negate().toString(b);
    var k;
    if(b == 16) k = 4;
    else if(b == 8) k = 3;
    else if(b == 2) k = 1;
    else if(b == 32) k = 5;
    else if(b == 4) k = 2;
    else return this.toRadix(b);
    var km = (1<<k)-1, d, m = false, r = "", i = this.t;
    var p = this.DB-(i*this.DB)%k;
    if(i-- > 0) {
      if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); }
      while(i >= 0) {
        if(p < k) {
          d = (this[i]&((1<<p)-1))<<(k-p);
          d |= this[--i]>>(p+=this.DB-k);
        }
        else {
          d = (this[i]>>(p-=k))&km;
          if(p <= 0) { p += this.DB; --i; }
        }
        if(d > 0) m = true;
        if(m) r += int2char(d);
      }
    }
    return m?r:"0";
  }

// (public) -this
  function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }

// (public) |this|
  function bnAbs() { return (this.s<0)?this.negate():this; }

// (public) return + if this > a, - if this < a, 0 if equal
  function bnCompareTo(a) {
    var r = this.s-a.s;
    if(r != 0) return r;
    var i = this.t;
    r = i-a.t;
    if(r != 0) return r;
    while(--i >= 0) if((r=this[i]-a[i]) != 0) return r;
    return 0;
  }

// returns bit length of the integer x
  function nbits(x) {
    var r = 1, t;
    if((t=x>>>16) != 0) { x = t; r += 16; }
    if((t=x>>8) != 0) { x = t; r += 8; }
    if((t=x>>4) != 0) { x = t; r += 4; }
    if((t=x>>2) != 0) { x = t; r += 2; }
    if((t=x>>1) != 0) { x = t; r += 1; }
    return r;
  }

// (public) return the number of bits in "this"
  function bnBitLength() {
    if(this.t <= 0) return 0;
    return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));
  }

// (protected) r = this << n*DB
  function bnpDLShiftTo(n,r) {
    var i;
    for(i = this.t-1; i >= 0; --i) r[i+n] = this[i];
    for(i = n-1; i >= 0; --i) r[i] = 0;
    r.t = this.t+n;
    r.s = this.s;
  }

// (protected) r = this >> n*DB
  function bnpDRShiftTo(n,r) {
    for(var i = n; i < this.t; ++i) r[i-n] = this[i];
    r.t = Math.max(this.t-n,0);
    r.s = this.s;
  }

// (protected) r = this << n
  function bnpLShiftTo(n,r) {
    var bs = n%this.DB;
    var cbs = this.DB-bs;
    var bm = (1<<cbs)-1;
    var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;
    for(i = this.t-1; i >= 0; --i) {
      r[i+ds+1] = (this[i]>>cbs)|c;
      c = (this[i]&bm)<<bs;
    }
    for(i = ds-1; i >= 0; --i) r[i] = 0;
    r[ds] = c;
    r.t = this.t+ds+1;
    r.s = this.s;
    r.clamp();
  }

// (protected) r = this >> n
  function bnpRShiftTo(n,r) {
    r.s = this.s;
    var ds = Math.floor(n/this.DB);
    if(ds >= this.t) { r.t = 0; return; }
    var bs = n%this.DB;
    var cbs = this.DB-bs;
    var bm = (1<<bs)-1;
    r[0] = this[ds]>>bs;
    for(var i = ds+1; i < this.t; ++i) {
      r[i-ds-1] |= (this[i]&bm)<<cbs;
      r[i-ds] = this[i]>>bs;
    }
    if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs;
    r.t = this.t-ds;
    r.clamp();
  }

// (protected) r = this - a
  function bnpSubTo(a,r) {
    var i = 0, c = 0, m = Math.min(a.t,this.t);
    while(i < m) {
      c += this[i]-a[i];
      r[i++] = c&this.DM;
      c >>= this.DB;
    }
    if(a.t < this.t) {
      c -= a.s;
      while(i < this.t) {
        c += this[i];
        r[i++] = c&this.DM;
        c >>= this.DB;
      }
      c += this.s;
    }
    else {
      c += this.s;
      while(i < a.t) {
        c -= a[i];
        r[i++] = c&this.DM;
        c >>= this.DB;
      }
      c -= a.s;
    }
    r.s = (c<0)?-1:0;
    if(c < -1) r[i++] = this.DV+c;
    else if(c > 0) r[i++] = c;
    r.t = i;
    r.clamp();
  }

// (protected) r = this * a, r != this,a (HAC 14.12)
// "this" should be the larger one if appropriate.
  function bnpMultiplyTo(a,r) {
    var x = this.abs(), y = a.abs();
    var i = x.t;
    r.t = i+y.t;
    while(--i >= 0) r[i] = 0;
    for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t);
    r.s = 0;
    r.clamp();
    if(this.s != a.s) BigInteger.ZERO.subTo(r,r);
  }

// (protected) r = this^2, r != this (HAC 14.16)
  function bnpSquareTo(r) {
    var x = this.abs();
    var i = r.t = 2*x.t;
    while(--i >= 0) r[i] = 0;
    for(i = 0; i < x.t-1; ++i) {
      var c = x.am(i,x[i],r,2*i,0,1);
      if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {
        r[i+x.t] -= x.DV;
        r[i+x.t+1] = 1;
      }
    }
    if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1);
    r.s = 0;
    r.clamp();
  }

// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
// r != q, this != m.  q or r may be null.
  function bnpDivRemTo(m,q,r) {
    var pm = m.abs();
    if(pm.t <= 0) return;
    var pt = this.abs();
    if(pt.t < pm.t) {
      if(q != null) q.fromInt(0);
      if(r != null) this.copyTo(r);
      return;
    }
    if(r == null) r = nbi();
    var y = nbi(), ts = this.s, ms = m.s;
    var nsh = this.DB-nbits(pm[pm.t-1]);	// normalize modulus
    if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }
    else { pm.copyTo(y); pt.copyTo(r); }
    var ys = y.t;
    var y0 = y[ys-1];
    if(y0 == 0) return;
    var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0);
    var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2;
    var i = r.t, j = i-ys, t = (q==null)?nbi():q;
    y.dlShiftTo(j,t);
    if(r.compareTo(t) >= 0) {
      r[r.t++] = 1;
      r.subTo(t,r);
    }
    BigInteger.ONE.dlShiftTo(ys,t);
    t.subTo(y,y);	// "negative" y so we can replace sub with am later
    while(y.t < ys) y[y.t++] = 0;
    while(--j >= 0) {
      // Estimate quotient digit
      var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);
      if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) {	// Try it out
        y.dlShiftTo(j,t);
        r.subTo(t,r);
        while(r[i] < --qd) r.subTo(t,r);
      }
    }
    if(q != null) {
      r.drShiftTo(ys,q);
      if(ts != ms) BigInteger.ZERO.subTo(q,q);
    }
    r.t = ys;
    r.clamp();
    if(nsh > 0) r.rShiftTo(nsh,r);	// Denormalize remainder
    if(ts < 0) BigInteger.ZERO.subTo(r,r);
  }

// (public) this mod a
  function bnMod(a) {
    var r = nbi();
    this.abs().divRemTo(a,null,r);
    if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);
    return r;
  }

// Modular reduction using "classic" algorithm
  function Classic(m) { this.m = m; }
  function cConvert(x) {
    if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
    else return x;
  }
  function cRevert(x) { return x; }
  function cReduce(x) { x.divRemTo(this.m,null,x); }
  function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }

  Classic.prototype.convert = cConvert;
  Classic.prototype.revert = cRevert;
  Classic.prototype.reduce = cReduce;
  Classic.prototype.mulTo = cMulTo;
  Classic.prototype.sqrTo = cSqrTo;

// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
// justification:
//         xy == 1 (mod m)
//         xy =  1+km
//   xy(2-xy) = (1+km)(1-km)
// x[y(2-xy)] = 1-k^2m^2
// x[y(2-xy)] == 1 (mod m^2)
// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
// JS multiply "overflows" differently from C/C++, so care is needed here.
  function bnpInvDigit() {
    if(this.t < 1) return 0;
    var x = this[0];
    if((x&1) == 0) return 0;
    var y = x&3;		// y == 1/x mod 2^2
    y = (y*(2-(x&0xf)*y))&0xf;	// y == 1/x mod 2^4
    y = (y*(2-(x&0xff)*y))&0xff;	// y == 1/x mod 2^8
    y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;	// y == 1/x mod 2^16
    // last step - calculate inverse mod DV directly;
    // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
    y = (y*(2-x*y%this.DV))%this.DV;		// y == 1/x mod 2^dbits
    // we really want the negative inverse, and -DV < y < DV
    return (y>0)?this.DV-y:-y;
  }

// Montgomery reduction
  function Montgomery(m) {
    this.m = m;
    this.mp = m.invDigit();
    this.mpl = this.mp&0x7fff;
    this.mph = this.mp>>15;
    this.um = (1<<(m.DB-15))-1;
    this.mt2 = 2*m.t;
  }

// xR mod m
  function montConvert(x) {
    var r = nbi();
    x.abs().dlShiftTo(this.m.t,r);
    r.divRemTo(this.m,null,r);
    if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
    return r;
  }

// x/R mod m
  function montRevert(x) {
    var r = nbi();
    x.copyTo(r);
    this.reduce(r);
    return r;
  }

// x = x/R mod m (HAC 14.32)
  function montReduce(x) {
    while(x.t <= this.mt2)	// pad x so am has enough room later
      x[x.t++] = 0;
    for(var i = 0; i < this.m.t; ++i) {
      // faster way of calculating u0 = x[i]*mp mod DV
      var j = x[i]&0x7fff;
      var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;
      // use am to combine the multiply-shift-add into one call
      j = i+this.m.t;
      x[j] += this.m.am(0,u0,x,i,0,this.m.t);
      // propagate carry
      while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; }
    }
    x.clamp();
    x.drShiftTo(this.m.t,x);
    if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
  }

// r = "x^2/R mod m"; x != r
  function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }

// r = "xy/R mod m"; x,y != r
  function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }

  Montgomery.prototype.convert = montConvert;
  Montgomery.prototype.revert = montRevert;
  Montgomery.prototype.reduce = montReduce;
  Montgomery.prototype.mulTo = montMulTo;
  Montgomery.prototype.sqrTo = montSqrTo;

// (protected) true iff this is even
  function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }

// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
  function bnpExp(e,z) {
    if(e > 0xffffffff || e < 1) return BigInteger.ONE;
    var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
    g.copyTo(r);
    while(--i >= 0) {
      z.sqrTo(r,r2);
      if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
      else { var t = r; r = r2; r2 = t; }
    }
    return z.revert(r);
  }

// (public) this^e % m, 0 <= e < 2^32
  function bnModPowInt(e,m) {
    var z;
    if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
    return this.exp(e,z);
  }

// protected
  BigInteger.prototype.copyTo = bnpCopyTo;
  BigInteger.prototype.fromInt = bnpFromInt;
  BigInteger.prototype.fromString = bnpFromString;
  BigInteger.prototype.clamp = bnpClamp;
  BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
  BigInteger.prototype.drShiftTo = bnpDRShiftTo;
  BigInteger.prototype.lShiftTo = bnpLShiftTo;
  BigInteger.prototype.rShiftTo = bnpRShiftTo;
  BigInteger.prototype.subTo = bnpSubTo;
  BigInteger.prototype.multiplyTo = bnpMultiplyTo;
  BigInteger.prototype.squareTo = bnpSquareTo;
  BigInteger.prototype.divRemTo = bnpDivRemTo;
  BigInteger.prototype.invDigit = bnpInvDigit;
  BigInteger.prototype.isEven = bnpIsEven;
  BigInteger.prototype.exp = bnpExp;

// public
  BigInteger.prototype.toString = bnToString;
  BigInteger.prototype.negate = bnNegate;
  BigInteger.prototype.abs = bnAbs;
  BigInteger.prototype.compareTo = bnCompareTo;
  BigInteger.prototype.bitLength = bnBitLength;
  BigInteger.prototype.mod = bnMod;
  BigInteger.prototype.modPowInt = bnModPowInt;

// "constants"
  BigInteger.ZERO = nbv(0);
  BigInteger.ONE = nbv(1);
// prng4.js - uses Arcfour as a PRNG

  function Arcfour() {
    this.i = 0;
    this.j = 0;
    this.S = new Array();
  }

// Initialize arcfour context from key, an array of ints, each from [0..255]
  function ARC4init(key) {
    var i, j, t;
    for(i = 0; i < 256; ++i)
      this.S[i] = i;
    j = 0;
    for(i = 0; i < 256; ++i) {
      j = (j + this.S[i] + key[i % key.length]) & 255;
      t = this.S[i];
      this.S[i] = this.S[j];
      this.S[j] = t;
    }
    this.i = 0;
    this.j = 0;
  }

  function ARC4next() {
    var t;
    this.i = (this.i + 1) & 255;
    this.j = (this.j + this.S[this.i]) & 255;
    t = this.S[this.i];
    this.S[this.i] = this.S[this.j];
    this.S[this.j] = t;
    return this.S[(t + this.S[this.i]) & 255];
  }

  Arcfour.prototype.init = ARC4init;
  Arcfour.prototype.next = ARC4next;

// Plug in your RNG constructor here
  function prng_newstate() {
    return new Arcfour();
  }

// Pool size must be a multiple of 4 and greater than 32.
// An array of bytes the size of the pool will be passed to init()
  var rng_psize = 256;
// Random number generator - requires a PRNG backend, e.g. prng4.js

// For best results, put code like
// <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
// in your main HTML document.

  var rng_state;
  var rng_pool;
  var rng_pptr;

// Mix in a 32-bit integer into the pool
  function rng_seed_int(x) {
    rng_pool[rng_pptr++] ^= x & 255;
    rng_pool[rng_pptr++] ^= (x >> 8) & 255;
    rng_pool[rng_pptr++] ^= (x >> 16) & 255;
    rng_pool[rng_pptr++] ^= (x >> 24) & 255;
    if(rng_pptr >= rng_psize) rng_pptr -= rng_psize;
  }

// Mix in the current time (w/milliseconds) into the pool
  function rng_seed_time() {
    rng_seed_int(new Date().getTime());
  }

// Initialize the pool with junk if needed.
  if(rng_pool == null) {
    rng_pool = new Array();
    rng_pptr = 0;
    var t;
    if(navigator.appName == "Netscape" && navigator.appVersion < "5" && window.crypto) {
      // Extract entropy (256 bits) from NS4 RNG if available
      var z = window.crypto.random(32);
      for(t = 0; t < z.length; ++t)
        rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
    }
    while(rng_pptr < rng_psize) {  // extract some randomness from Math.random()
      t = Math.floor(65536 * Math.random());
      rng_pool[rng_pptr++] = t >>> 8;
      rng_pool[rng_pptr++] = t & 255;
    }
    rng_pptr = 0;
    rng_seed_time();
    //rng_seed_int(window.screenX);
    //rng_seed_int(window.screenY);
  }

  function rng_get_byte() {
    if(rng_state == null) {
      rng_seed_time();
      rng_state = prng_newstate();
      rng_state.init(rng_pool);
      for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
        rng_pool[rng_pptr] = 0;
      rng_pptr = 0;
      //rng_pool = null;
    }
    // TODO: allow reseeding after first request
    return rng_state.next();
  }

  function rng_get_bytes(ba) {
    var i;
    for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
  }

  function SecureRandom() {}

  SecureRandom.prototype.nextBytes = rng_get_bytes;
// Depends on jsbn.js and rng.js

// convert a (hex) string to a bignum object
  function parseBigInt(str,r) {
    return new BigInteger(str,r);
  }

  function linebrk(s,n) {
    var ret = "";
    var i = 0;
    while(i + n < s.length) {
      ret += s.substring(i,i+n) + "\n";
      i += n;
    }
    return ret + s.substring(i,s.length);
  }

  function byte2Hex(b) {
    if(b < 0x10)
      return "0" + b.toString(16);
    else
      return b.toString(16);
  }

// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
  function pkcs1pad2(s,n) {
    if(n < s.length + 11) {
      alert("Message too long for RSA");
      return null;
    }
    var ba = new Array();
    var i = s.length - 1;
    while(i >= 0 && n > 0) ba[--n] = s.charCodeAt(i--);
    ba[--n] = 0;
    var rng = new SecureRandom();
    var x = new Array();
    while(n > 2) { // random non-zero pad
      x[0] = 0;
      while(x[0] == 0) rng.nextBytes(x);
      ba[--n] = x[0];
    }
    ba[--n] = 2;
    ba[--n] = 0;
    return new BigInteger(ba);
  }

// "empty" RSA key constructor
  function RSAKey() {
    this.n = null;
    this.e = 0;
    this.d = null;
    this.p = null;
    this.q = null;
    this.dmp1 = null;
    this.dmq1 = null;
    this.coeff = null;
  }

// Set the public key fields N and e from hex strings
  function RSASetPublic(N,E) {
    if(N != null && E != null && N.length > 0 && E.length > 0) {
      this.n = parseBigInt(N,16);
      this.e = parseInt(E,16);
    }
    else
      alert("Invalid RSA public key");
  }

// Perform raw public operation on "x": return x^e (mod n)
  function RSADoPublic(x) {
    return x.modPowInt(this.e, this.n);
  }

// Return the PKCS#1 RSA encryption of "text" as an even-length hex string
  function RSAEncrypt(text) {
    var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
    if(m == null) return null;
    var c = this.doPublic(m);
    if(c == null) return null;
    var h = c.toString(16);
    if((h.length & 1) == 0) return h; else return "0" + h;
  }

// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
  function RSAEncryptB64(text) {
    var h = this.encrypt(text);
    if(h) return hex2b64(h); else return null;
  }

// protected
  RSAKey.prototype.doPublic = RSADoPublic;

// public
  RSAKey.prototype.setPublic = RSASetPublic;
  RSAKey.prototype.encrypt = RSAEncrypt;
  RSAKey.prototype.encrypt_b64 = RSAEncryptB64;

// PUBLIC METHODS:
window.RSAKey = RSAKey;
//window.hex2b64 = hex2b64;
})();
var Gilt;
if (!Gilt) {
  Gilt = {};
}
if (!Gilt.GiftCards) {
  Gilt.GiftCards = {};
}
(function() {
  Gilt.GiftCards.showCreateGCModal = function(view) {
    var d = createOrResetModal(view || "create_gc");
    d.dialog("open");
  };
  Gilt.GiftCards.startRedeem = function(cards) {
    var d = createOrResetModal("activate_gc", " ");
    d.find("#activate_gc, #redeem_gc")
      .find("span.recip_name").text(gg.Usermeta.data().display_name).end()
      .find("span.recip_email").text(fl.Util.readCookie("email")).end()
      .find("span.card_amount").text(fl.Formatter.currency(cards[0].amount)).end();
    d.dialog("open");
  };

  var RSA;
  var getRSA = function(callback) {
    if (!RSA) {
      $.getJSON(Gilt.GiftCards.paymentServiceUri + "/get_publickey?callback=?", function(data) {
        RSA = new RSAKey();
        RSA.setPublic(data.data.key_data.public_modulus_hex, data.data.key_data.public_exponent_hex);
        if (callback) {
          callback();
        }
      });
    } else {
      if (callback) {
        callback();
      }
    }
  };

  // Private Functions:
  var createOrResetModal = function(default_view, title) {
    var d = fl.Util.getDialog("gift_card_modal", {
      title: title || Locale.gift_card,
      width: 880,
      height: 495 + 41,
      clickOverlay: false,
      additionalInit: function(d) {
        d.find("#theme_carousel").carousel({
          autoRotate: false,
          transitions: [null, []],
          showFooter: false
          //customFooterTemplate: function(i) {
          //  return "<div><img src='" + d.find("#theme_carousel ul.pics li:eq(" + (i) + ") img").attr("src") + "'/><div class='overlay'></div>" +
          //         d.find("#theme_carousel ul.titles li:eq(" + (i) + ") span:not(.title_right)").text() + "</div>";
          //}
        }).bind("carouselframe", function() {
            //$("#create_gc form #gc_theme_name").val("theme_" + ($("#theme_carousel .ui-state-active:first").attr("class").match(/ui-icon-numeral-(\d)/)[1] - 1));
            var index = $("#theme_carousel ul.titles li:visible").attr("class").match(/ui-carousel-state-(\d)+/)[1];
            var index_val = $("#create_gc form #gc_theme_name option:eq(" + index + ")").val()
            $("#create_gc form #gc_theme_name").val(index_val);
            $("#create_gc form #gc_theme_name").prev("a.ui-selectmenu").find("span.ui-selectmenu-status").text($("#create_gc form #gc_theme_name option:selected").text());
          });
        d.closest(".ui-dialog").show();
        d.find("div.gc_view").show();
        //var unitWidth = $("#theme_carousel span.ui-carousel-footer-group span.ui-icon-numeral-2").offset().left -
        //                $("#theme_carousel span.ui-carousel-footer-group span.ui-icon-numeral-1").offset().left;
        $("#gift_card_modal select").selectmenu({
          style: "dropdown",
          change: function() {
            if ($(this).hasClass("error")) {
              $(this).closest("form").validate().element(this);
            }
          }
        }).each(function() {
          $(this).data("selectmenu").newelement.insertBefore($(this));
        });
        d.find("div.gc_view").hide();
        d.closest(".ui-dialog").hide();
        /*var numThumbsInView = 5;
        $("#theme_carousel span.ui-carousel-footer-group span.ui-icon-arrow-1-w")
          .unbind("click")
          .click(function() {
            var newLeft = parseInt($("#theme_carousel span.ui-carousel-footer-group").css("left")) + unitWidth;
            if (0 <= newLeft) {
              newLeft = -unitWidth * ($("#theme_carousel span.ui-carousel-footer-group span").length - numThumbsInView * 2);
              $("#theme_carousel span.ui-carousel-footer-group").css({ left: newLeft - unitWidth });

            }
            $("#theme_carousel span.ui-carousel-footer-group").animate({ left: newLeft });
          })
          .appendTo("#theme_carousel div.ui-carousel-footer");
        $("#theme_carousel span.ui-carousel-footer-group span.ui-icon-arrow-1-e")
          .unbind("click")
          .click(function() {
            var newLeft = parseInt($("#theme_carousel span.ui-carousel-footer-group").css("left")) - unitWidth;
            if (-unitWidth * ($("#theme_carousel span.ui-carousel-footer-group span").length - numThumbsInView) >= newLeft) {
              newLeft = -unitWidth * numThumbsInView;
              $("#theme_carousel span.ui-carousel-footer-group").css({ left: newLeft + unitWidth });
            }
            $("#theme_carousel span.ui-carousel-footer-group").animate({ left: newLeft });
          })
          .appendTo("#theme_carousel div.ui-carousel-footer");
        $("<div class='left_block'></div>").appendTo("#theme_carousel div.ui-carousel-footer");
        $("<div class='right_block'></div>").appendTo("#theme_carousel div.ui-carousel-footer");
        var preSet = $("#theme_carousel span.ui-carousel-footer-group span.ui-icon:lt(" + numThumbsInView + ")")
          .clone(true);
        $("#theme_carousel span.ui-carousel-footer-group span.ui-icon:gt(" + ($("#theme_carousel span.ui-carousel-footer-group span.ui-icon").length - numThumbsInView - 1) + ")")
          .clone(true)
          .prependTo("#theme_carousel span.ui-carousel-footer-group");
        preSet.appendTo("#theme_carousel span.ui-carousel-footer-group");
        $("#theme_carousel span.ui-carousel-footer-group").css({ left: -unitWidth * numThumbsInView });*/
        d.find("#create_gc form #gc_theme_name").change(function() {
          var index = $(this).find("option:selected").prevAll().length;
          //$("#theme_carousel span.ui-carousel-footer-group span.ui-icon-numeral-" + (index + 1)).click();
          d.find("#theme_carousel").carousel("frame", index);
          //$("#theme_carousel span.ui-carousel-footer-group").css({ left: -unitWidth * (numThumbsInView + index) });
        });
        d.find("#create_gc form #gc_amount").change(function() {
          if (-1 == $(this).val()) {
            if (288 == $("#create_gc form #left_pane").width()) {
              $("#create_gc form #gc_amount").prev("a.ui-selectmenu").add("#create_gc form #left_pane").animate({ width: 137 });
            }
          } else {
            if (137 == $("#create_gc form #left_pane").width()) {
              $("#create_gc form #gc_amount").prev("a.ui-selectmenu").add("#create_gc form #left_pane").animate({ width: 288 });
            }
          }
        });
        fl.Formatter.creditCardAsYouType(d.find("#credit_card_gc form #add_cc_number"));
        fl.Formatter.phoneNumberAsYouType(d.find("#credit_card_gc form #add_cc_phone"));
        $("#credit_card_gc form #add_cc_cvn")
          .focus(function() {
          $("#credit_card_gc form div.cvn_info").show("slide", { direction: "up" });
        }).blur(function() {
          $("#credit_card_gc form div.cvn_info").hide("slide", { direction: "up" });
        });
        d.find("#create_gc form input, #create_gc form a.ui-selectmenu").keypress(function(ev) {
          if (13 == ev.which) {
            if (checkCreateForm()) {
              slide($("#create_gc"), $("#confirm_gc"), true);
            }
          }
        });
        d.find("#create_gc div.gc_actions a.preview").click(function(ev) {
          ev.preventDefault();
          if (checkCreateForm()) {
            slide($("#create_gc"), $("#preview_gc"), true);
          }
        });
        d.find("#create_gc div.gc_actions a.continue").click(function(ev) {
          ev.preventDefault();
          if (checkCreateForm()) {
            slide($("#create_gc"), $("#confirm_gc"), true);
          }
        });
        d.find("#preview_gc div.gc_actions a.back").click(function(ev) {
          ev.preventDefault();
          slide($("#preview_gc"), $("#create_gc"), false);
        });
        d.find("#preview_gc div.gc_actions a.continue").click(function(ev) {
          ev.preventDefault();
          slide($("#preview_gc"), $("#confirm_gc"), true);
        });
        d.find("#confirm_gc div.gc_actions a.back").click(function(ev) {
          ev.preventDefault();
          slide($("#confirm_gc"), $("#create_gc"), false);
        });
        d.find("#confirm_gc a.add_cc").click(function(ev) {
          ev.preventDefault();
          slide($("#confirm_gc"), $("#credit_card_gc"), true);
        });
        d.find("#credit_card_gc div.gc_actions a.back").click(function(ev) {
          ev.preventDefault();
          slide($("#credit_card_gc"), $("#confirm_gc"), false);
        });
        d.find("#confirm_gc div.gc_actions a.purchase").click(function(ev) {
          ev.preventDefault();
          if (credit_card_list.length) {
            submitGC();
          } else {
            slide($("#confirm_gc"), $("#credit_card_gc"), true);
          }
        });
        d.find("#credit_card_gc form input, #create_gc form a.ui-selectmenu").keypress(function(ev) {
          if (13 == ev.which) {
            d.find("#credit_card_gc div.gc_actions a.continue").click();
          }
        });
        d.find("#credit_card_gc div.gc_actions a.continue").click(function(ev) {
          ev.preventDefault();
          $("#gc_add_cc_errors").html("").hide();
          if (checkCCForm()) {
            getRSA(function() {
              var data = {
                user_guid: fl.Util.readHashedCookie('guid'),
                first_name: $("#add_cc_first_name").val(),
                last_name: $("#add_cc_last_name").val(),
                exp_date: $("#add_cc_month").val() + "/" + $("#add_cc_year").val().substring(2),
                cvn: $("#add_cc_cvn").val(),
                cc_number_enc_hex: RSA.encrypt($("#add_cc_number").val().replace(/\s/g, "")),
                "billing_address[first_name]": $("#add_cc_first_name").val(),
                "billing_address[last_name]": $("#add_cc_last_name").val(),
                "billing_address[street_line1]": $("#add_cc_street1").val(),
                "billing_address[street_line2]": $("#add_cc_street2").val(),
                "billing_address[city]": $("#add_cc_city").val(),
                "billing_address[state]": $("#add_cc_state").val(),
                "billing_address[postal_code]": $("#add_cc_zip").val(),
                "billing_address[phone_number]": $("#add_cc_phone").val(),
                "billing_address[country_id]": $("#add_cc_country_id").val(),
                "billing_address[address_type]": "h",
                verify_address: true
                //subsite_id: Gilt.Subsite.current_subsite_id
              };
              $.getJSON(Gilt.GiftCards.paymentServiceUri + "/add_credit_card?callback=?", data, function(return_data) {
                if (!verifyAddress(return_data)) {
                  data.verify_address = false;
                  $.getJSON(Gilt.GiftCards.paymentServiceUri + "/add_credit_card?callback=?", data, function(return_data) {
                    handleCCResponse(return_data);
                  });
                } else {
                  handleCCResponse(return_data);
                }
              });
            });
          }
        });
        d.find("#thanks_gc div.gc_actions a.continue").click(function(ev) {
          ev.preventDefault();
          d.dialog("close");
        });
        d.find("#thanks_gc div.gc_actions a.back").click(function(ev) {
          ev.preventDefault();
          resetGCModal();
          slide($("#thanks_gc"), $("#create_gc"), true);
        });
        d.find("#activate_gc div.gc_actions a.continue").click(function(ev) {
          ev.preventDefault();
          // TODO: redeem
          slide($("#activate_gc"), $("#redeem_gc"), true);
        });
        d.find("#redeem_gc div.gc_actions a.continue").click(function(ev) {
          ev.preventDefault();
          d.dialog("close");
        });
      }
    });
    var popFieldsFromCreate = function() {
      $("#preview_gc span.theme_name, #confirm_gc #confirm_theme, #confirm_gc span.theme_name").html($("#theme_carousel ul.pics li:visible img").attr("alt"));
      $("#preview_gc #gc_preview_image img, #confirm_gc div.preview img").attr("src", $("#theme_carousel ul.pics li:visible img").attr("src"));
      $("#preview_gc span.sender_name, #confirm_gc #confirm_sender_name, #confirm_gc span.sender_name").html($("#create_gc #gc_sender_name").val() || "&nbsp;");
      $("#preview_gc span.recip_name, #confirm_gc #confirm_recip_name, #confirm_gc span.recip_name").html($("#create_gc #gc_recip_name").val() || "&nbsp;");
      $("#confirm_gc #confirm_recip_email, #confirm_gc span.recip_email, #thanks_gc span.recip_email").html($("#create_gc #gc_recip_email").val() || "&nbsp;");
      $("#preview_gc span.message, #confirm_gc #confirm_message, #confirm_gc span.message").html($("#create_gc #gc_message").val() || "&nbsp;");
      var amount = $("#create_gc #gc_amount").val();
      if (-1 == amount) {
        amount = $("#create_gc #gc_other_amount").val();
      }
      $("#preview_gc span.card_amount, #confirm_gc #confirm_amount, #confirm_gc span.card_amount, #thanks_gc span.card_amount").html(fl.Formatter.currency(amount));
    };
    var checkCreateForm = function() {
      if ($("#create_gc form").validate().element($("#gc_amount")) && $("#create_gc form").validate().form()) {
        popFieldsFromCreate();
        return true;
      } else {
        $("#create_gc form").validate().form();
        $("#create_gc form").validate().element($("#gc_amount")); // for some reason, selects have to be validated individually
      }
      return false;
    };
    var checkCCForm = function() {
      if ($("#credit_card_gc form").validate().element($("#add_cc_month")) &&
          $("#credit_card_gc form").validate().element($("#add_cc_year")) &&
          $("#credit_card_gc form").validate().element($("#add_cc_state")) &&
          $("#credit_card_gc form").validate().form()) {
        return true;
      } else {
        $("#credit_card_gc form").validate().form();
        $("#credit_card_gc form").validate().element($("#add_cc_month"));
        $("#credit_card_gc form").validate().element($("#add_cc_year"));
        $("#credit_card_gc form").validate().element($("#add_cc_state"));
      }
      return false;
    };
    var slide = function(from, to, forward, callback) {
      from
        .children("div")
          .filter(":not(.gc_inner)")
            .filter(".gc_notice")
              .hide("slide", { direction: "down" })
            .others()
              .fadeOut()
            .end()
          .others()
            .hide("slide", { direction: forward ? "left" : "right" }, function() {
              from.hide().children("div").show();
            });
      to.show()
        .children("div")
          .hide()
          .filter(":not(.gc_inner)")
            .filter(".gc_notice")
              .show("slide", { direction: "down" })
            .others()
              .fadeIn()
            .end()
          .others()
            .show("slide", { direction: forward ? "right" : "left" }, function() {
              if (callback) {
                callback();
              }
            });
    };
    var submitGC = function() {
      var cur_CC = $(credit_card_list).filter(function() {
        return this.is_default;
      });
      if (!cur_CC.length) {
        $("#gc_submit_errors").html(Locale.please_select_a_credit_card).show();
      } else {
        $("#gc_submit_errors").html("").hide();
        $.post("/bb/gift_certificates/create", {
          "gift_certificate[credit_card_guid]": cur_CC[0].cc_guid,
          "gift_certificate[theme]": $("#create_gc form #gc_theme_name").val().replace("theme_", ""),
          "gift_certificate[subtotal]": $("#confirm_amount").text().replace(Locale.currency_symbol, "").replace(Locale.currency_group_delimiter, ""),
          "gift_certificate[recipient_email]": $("#confirm_recip_email").text(),
          "gift_certificate[recipient_name]": $("#confirm_recip_name").text(),
          "gift_certificate[sender_name]": $("#confirm_sender_name").text(),
          "gift_certificate[message]": $("#confirm_message").text()
        }, function(response) {
          if (response.data && response.data.success) {
            slide($("#confirm_gc, #credit_card_gc"), $("#thanks_gc"), true);
          } else {
            $("#gc_submit_errors").html(response.data ? response.data.msg : response.msg).show();
          }
        }, 'json');
      }
    };
    var handleCCResponse = function(return_data) {
      if (return_data.data && return_data.data.success) {
        $(credit_card_list).each(function() {
          if (this.is_default) {
            this.is_default = false;
            return false;
          }
        });
        var new_cc = {
          is_default: true,
          guid: return_data.data.card_data.cc_guid,
          cc_last_four: return_data.data.card_data.cc_last_four,
          exp_date: return_data.data.card_data.exp_date,
          cc_type: $("#add_cc_number").data("creditcardtype")
        };
        credit_card_list.push(new_cc);
        d.find("label.no_cc").hide();
        d.find("div.has_cc").show().find("form div.cc_container").append(formatCC(new_cc));
        if (3 < credit_card_list.length) {
          $("#confirm_gc div.has_cc").removeClass('few_ccs');
        }
        d.find("#credit_card_gc form").validate().resetForm();
        d.find("#credit_card_gc select").each(function() {
          $(this).selectmenu("value", "");
        });
        slide($("#credit_card_gc"), $("#confirm_gc"), false);
      } else {
        if (return_data.data && return_data.data.auth_response) {
          $("#gc_add_cc_errors").html(Gilt.GiftCards.ccErrorCodes[return_data.data.auth_response.gilt_result_code] || "").show();
        } else {
          $("#gc_add_cc_errors").html(return_data.data ? return_data.data.msg : return_data.msg).show();
        }
      }
    };
    var verifyAddress = function(return_data) {
      var isHashEmpty = function(hash) {
        for (var key in hash) {
          if (hash.hasOwnProperty(key)) {
            return false;
          }
        }
        return true;
      };
      var minor_address_verification_check = function(return_data, address_verification) {
        if (!return_data.data.msg) {
          return_data.data.msg = "";
        }
        return_data.data.success = true;
        if (!address_verification.gilt_error_code && !isHashEmpty(address_verification.suggested_field_changes) ) {
          var major_fields = {"zip" : "Zip code", "city" : "City", state : "State"};
          for (var field in major_fields) {
            if (address_verification.suggested_field_changes[field]) {
              return_data.data.msg += Locale.field_does_not_match_address_provided(major_fields[field], address_verification.suggested_field_changes[field]) + "<br/>";
              return_data.data.success = false;
            }
            address_verification.suggested_field_changes[field] = null;
            delete address_verification.suggested_field_changes[field];
          }

          if (!return_data.data.msg.length && !isHashEmpty(address_verification.suggested_field_changes)) {
            return true;
          }
        } else if (address_verification.provider_error) {
          return_data.data.msg += Locale.address_verification_provider_error(address_verification.provider_error, address_verification.provider_error_msg);
          return_data.data.success = false;
        }
        return false;
      };
      var address_verification = return_data.data.verify_address;
      if (address_verification && 1 == address_verification.gilt_error_code || minor_address_verification_check(return_data, address_verification) ) {
        return false;
      }
      return true;
    };

    // RESET:
    var resetGCModal = function() {
      d.find("select").hide(); // selects get reshown by fl.Util.getDialog() on close dialog
      $("#create_gc form #left_pane").width(288);
      $("#gc_add_cc_errors, #gc_submit_errors").html("").hide();
      d.find("form")
         .find("label.error").remove().end()
         .find("input").val("").end()
         .find("select").each(function() {
          $(this).val($(this).find("option:first").val());
          $(this).prev("a.ui-selectmenu").find("span.ui-selectmenu-status").text($(this).find("option:first").text());
        }).end()
         .find("textarea").each(function() {
          $(this).val($(this).attr("data-default-value"));
        }).end()
         .find("#gc_other_amount").val(Locale.currency_symbol).end()
         .find("#gc_sender_name").val(gg.Usermeta.data().display_name);
      d.find("div.gc_view").hide().filter("#" + default_view).show();
    };
    resetGCModal();

    // START CC DATA REQUEST:
    var credit_card_list;
    var formatCC = function(cc, first) {
      return "<div class='cc" + (cc.is_default ? " default" : "") + (first ? " first" : "") + "'><div>" + cc.cc_type + " xxxx-" + cc.cc_last_four + "<br/>" + "Exp: " + $.strftime("%b %Y", new Date(cc.exp_date.replace("/", "/01/"))) + "</div></div>";
    };
    $("#confirm_gc div.has_cc div.cc").live("click", function() {
      $("#confirm_gc div.has_cc div.cc.default").removeClass("default");
      $(this).addClass("default");
      $(credit_card_list).each(function() {
        if (this.is_default) {
          this.is_default = false;
          return false;
        }
      });
      credit_card_list[$(this).prevAll().length].is_default = true;
    });
    $.getJSON(Gilt.GiftCards.paymentServiceUri + "/card_list?callback=?", { user_guid: fl.Util.readHashedCookie('guid') }, function(credit_cards) {
      credit_card_list = credit_cards.data.card_list;
      if (credit_card_list.length) {
        d.find("div.has_cc").empty();
        $(credit_card_list).each(function(i, cc) {
          d.find("div.has_cc").append(formatCC(cc, !i));
        });
        d.find("span.no_cc").hide();
        d.find("div.has_cc").show();
        if (4 > credit_card_list.length) {
          $("#confirm_gc div.has_cc").addClass('few_ccs');
        }
      } else {
        d.find("span.no_cc").show();
        d.find("div.has_cc").hide();
      }
    });
    return d;
  };
})();


