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

var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };

/**
 * Set the variable that indicates if JavaScript behaviors should be applied
 */
Drupal.jsEnabled = true;

/**
 * Attach all registered behaviors to a page element.
 *
 * Behaviors are event-triggered actions that attach to page elements, enhancing
 * default non-Javascript UIs. Behaviors are registered in the Drupal.behaviors
 * object as follows:
 * @code
 *    Drupal.behaviors.behaviorName = function () {
 *      ...
 *    };
 * @endcode
 *
 * Drupal.attachBehaviors is added below to the jQuery ready event and so
 * runs on initial page load. Developers implementing AHAH/AJAX in their
 * solutions should also call this function after new page content has been
 * loaded, feeding in an element to be processed, in order to attach all
 * behaviors to the new content.
 *
 * Behaviors should use a class in the form behaviorName-processed to ensure
 * the behavior is attached only once to a given element. (Doing so enables
 * the reprocessing of given elements, which may be needed on occasion despite
 * the ability to limit behavior attachment to a particular element.)
 *
 * @param context
 *   An element to attach behaviors to. If none is given, the document element
 *   is used.
 */
Drupal.attachBehaviors = function(context) {
  context = context || document;
  // Execute all of them.
  jQuery.each(Drupal.behaviors, function() {
    this(context);
  });
};

/**
 * Encode special characters in a plain-text string for display as HTML.
 */
Drupal.checkPlain = function(str) {
  str = String(str);
  var replace = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' };
  for (var character in replace) {
    var regex = new RegExp(character, 'g');
    str = str.replace(regex, replace[character]);
  }
  return str;
};

/**
 * Translate strings to the page language or a given language.
 *
 * See the documentation of the server-side t() function for further details.
 *
 * @param str
 *   A string containing the English string to translate.
 * @param args
 *   An object of replacements pairs to make after translation. Incidences
 *   of any key in this array are replaced with the corresponding value.
 *   Based on the first character of the key, the value is escaped and/or themed:
 *    - !variable: inserted as is
 *    - @variable: escape plain text to HTML (Drupal.checkPlain)
 *    - %variable: escape text and theme as a placeholder for user-submitted
 *      content (checkPlain + Drupal.theme('placeholder'))
 * @return
 *   The translated string.
 */
Drupal.t = function(str, args) {
  // Fetch the localized version of the string.
  if (Drupal.locale.strings && Drupal.locale.strings[str]) {
    str = Drupal.locale.strings[str];
  }

  if (args) {
    // Transform arguments before inserting them
    for (var key in args) {
      switch (key.charAt(0)) {
        // Escaped only
        case '@':
          args[key] = Drupal.checkPlain(args[key]);
        break;
        // Pass-through
        case '!':
          break;
        // Escaped and placeholder
        case '%':
        default:
          args[key] = Drupal.theme('placeholder', args[key]);
          break;
      }
      str = str.replace(key, args[key]);
    }
  }
  return str;
};

/**
 * Format a string containing a count of items.
 *
 * This function ensures that the string is pluralized correctly. Since Drupal.t() is
 * called by this function, make sure not to pass already-localized strings to it.
 *
 * See the documentation of the server-side format_plural() function for further details.
 *
 * @param count
 *   The item count to display.
 * @param singular
 *   The string for the singular case. Please make sure it is clear this is
 *   singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
 *   Do not use @count in the singular string.
 * @param plural
 *   The string for the plural case. Please make sure it is clear this is plural,
 *   to ease translation. Use @count in place of the item count, as in "@count
 *   new comments".
 * @param args
 *   An object of replacements pairs to make after translation. Incidences
 *   of any key in this array are replaced with the corresponding value.
 *   Based on the first character of the key, the value is escaped and/or themed:
 *    - !variable: inserted as is
 *    - @variable: escape plain text to HTML (Drupal.checkPlain)
 *    - %variable: escape text and theme as a placeholder for user-submitted
 *      content (checkPlain + Drupal.theme('placeholder'))
 *   Note that you do not need to include @count in this array.
 *   This replacement is done automatically for the plural case.
 * @return
 *   A translated string.
 */
Drupal.formatPlural = function(count, singular, plural, args) {
  var args = args || {};
  args['@count'] = count;
  // Determine the index of the plural form.
  var index = Drupal.locale.pluralFormula ? Drupal.locale.pluralFormula(args['@count']) : ((args['@count'] == 1) ? 0 : 1);

  if (index == 0) {
    return Drupal.t(singular, args);
  }
  else if (index == 1) {
    return Drupal.t(plural, args);
  }
  else {
    args['@count['+ index +']'] = args['@count'];
    delete args['@count'];
    return Drupal.t(plural.replace('@count', '@count['+ index +']'));
  }
};

/**
 * Generate the themed representation of a Drupal object.
 *
 * All requests for themed output must go through this function. It examines
 * the request and routes it to the appropriate theme function. If the current
 * theme does not provide an override function, the generic theme function is
 * called.
 *
 * For example, to retrieve the HTML that is output by theme_placeholder(text),
 * call Drupal.theme('placeholder', text).
 *
 * @param func
 *   The name of the theme function to call.
 * @param ...
 *   Additional arguments to pass along to the theme function.
 * @return
 *   Any data the theme function returns. This could be a plain HTML string,
 *   but also a complex object.
 */
Drupal.theme = function(func) {
  for (var i = 1, args = []; i < arguments.length; i++) {
    args.push(arguments[i]);
  }

  return (Drupal.theme[func] || Drupal.theme.prototype[func]).apply(this, args);
};

/**
 * Parse a JSON response.
 *
 * The result is either the JSON object, or an object with 'status' 0 and 'data' an error message.
 */
Drupal.parseJson = function (data) {
  if ((data.substring(0, 1) != '{') && (data.substring(0, 1) != '[')) {
    return { status: 0, data: data.length ? data : Drupal.t('Unspecified error') };
  }
  return eval('(' + data + ');');
};

/**
 * Freeze the current body height (as minimum height). Used to prevent
 * unnecessary upwards scrolling when doing DOM manipulations.
 */
Drupal.freezeHeight = function () {
  Drupal.unfreezeHeight();
  var div = document.createElement('div');
  $(div).css({
    position: 'absolute',
    top: '0px',
    left: '0px',
    width: '1px',
    height: $('body').css('height')
  }).attr('id', 'freeze-height');
  $('body').append(div);
};

/**
 * Unfreeze the body height
 */
Drupal.unfreezeHeight = function () {
  $('#freeze-height').remove();
};

/**
 * Wrapper around encodeURIComponent() which avoids Apache quirks (equivalent of
 * drupal_urlencode() in PHP). This function should only be used on paths, not
 * on query string arguments.
 */
Drupal.encodeURIComponent = function (item, uri) {
  uri = uri || location.href;
  item = encodeURIComponent(item).replace(/%2F/g, '/');
  return (uri.indexOf('?q=') != -1) ? item : item.replace(/%26/g, '%2526').replace(/%23/g, '%2523').replace(/\/\//g, '/%252F');
};

/**
 * Get the text selection in a textarea.
 */
Drupal.getSelection = function (element) {
  if (typeof(element.selectionStart) != 'number' && document.selection) {
    // The current selection
    var range1 = document.selection.createRange();
    var range2 = range1.duplicate();
    // Select all text.
    range2.moveToElementText(element);
    // Now move 'dummy' end point to end point of original range.
    range2.setEndPoint('EndToEnd', range1);
    // Now we can calculate start and end points.
    var start = range2.text.length - range1.text.length;
    var end = start + range1.text.length;
    return { 'start': start, 'end': end };
  }
  return { 'start': element.selectionStart, 'end': element.selectionEnd };
};

/**
 * Build an error message from ahah response.
 */
Drupal.ahahError = function(xmlhttp, uri) {
  if (xmlhttp.status == 200) {
    if (jQuery.trim(xmlhttp.responseText)) {
      var message = Drupal.t("An error occurred. \n@uri\n@text", {'@uri': uri, '@text': xmlhttp.responseText });
    }
    else {
      var message = Drupal.t("An error occurred. \n@uri\n(no information available).", {'@uri': uri });
    }
  }
  else {
    var message = Drupal.t("An HTTP error @status occurred. \n@uri", {'@uri': uri, '@status': xmlhttp.status });
  }
  return message.replace(/\n/g, '<br />');
}

// Global Killswitch on the <html> element
$(document.documentElement).addClass('js');
// Attach all behaviors.
$(document).ready(function() {
  Drupal.attachBehaviors(this);
});

/**
 * The default themes.
 */
Drupal.theme.prototype = {

  /**
   * Formats text for emphasized display in a placeholder inside a sentence.
   *
   * @param str
   *   The text to format (plain-text).
   * @return
   *   The formatted text (html).
   */
  placeholder: function(str) {
    return '<em>' + Drupal.checkPlain(str) + '</em>';
  }
};
;
/*!
 * jQuery Form Plugin
 * version: 2.47 (04-SEP-2010)
 * @requires jQuery v1.3.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($) {

/*
	Usage Note:
	-----------
	Do not use both ajaxSubmit and ajaxForm on the same form.  These
	functions are intended to be exclusive.  Use ajaxSubmit if you want
	to bind your own submit handler to the form.  For example,

	$(document).ready(function() {
		$('#myForm').bind('submit', function() {
			$(this).ajaxSubmit({
				target: '#output'
			});
			return false; // <-- important!
		});
	});

	Use ajaxForm when you want the plugin to manage all the event binding
	for you.  For example,

	$(document).ready(function() {
		$('#myForm').ajaxForm({
			target: '#output'
		});
	});

	When using ajaxForm, the ajaxSubmit function will be invoked for you
	at the appropriate time.
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
	// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
	if (!this.length) {
		log('ajaxSubmit: skipping submit process - no element selected');
		return this;
	}

	if (typeof options == 'function') {
		options = { success: options };
	}

	var url = $.trim(this.attr('action'));
	if (url) {
		// clean url (don't include hash vaue)
		url = (url.match(/^([^#]+)/)||[])[1];
	}
	url = url || window.location.href || '';

	options = $.extend(true, {
		url:  url,
		type: this.attr('method') || 'GET',
		iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
	}, options);

	// hook for manipulating the form data before it is extracted;
	// convenient for use with rich editors like tinyMCE or FCKEditor
	var veto = {};
	this.trigger('form-pre-serialize', [this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
		return this;
	}

	// provide opportunity to alter form data before it is serialized
	if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSerialize callback');
		return this;
	}

	var n,v,a = this.formToArray(options.semantic);
	if (options.data) {
		options.extraData = options.data;
		for (n in options.data) {
			if(options.data[n] instanceof Array) {
				for (var k in options.data[n]) {
					a.push( { name: n, value: options.data[n][k] } );
				}
			}
			else {
				v = options.data[n];
				v = $.isFunction(v) ? v() : v; // if value is fn, invoke it
				a.push( { name: n, value: v } );
			}
		}
	}

	// give pre-submit callback an opportunity to abort the submit
	if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSubmit callback');
		return this;
	}

	// fire vetoable 'validate' event
	this.trigger('form-submit-validate', [a, this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
		return this;
	}

	var q = $.param(a);

	if (options.type.toUpperCase() == 'GET') {
		options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
		options.data = null;  // data is null for 'get'
	}
	else {
		options.data = q; // data is the query string for 'post'
	}

	var $form = this, callbacks = [];
	if (options.resetForm) {
		callbacks.push(function() { $form.resetForm(); });
	}
	if (options.clearForm) {
		callbacks.push(function() { $form.clearForm(); });
	}

	// perform a load on the target only if dataType is not provided
	if (!options.dataType && options.target) {
		var oldSuccess = options.success || function(){};
		callbacks.push(function(data) {
			var fn = options.replaceTarget ? 'replaceWith' : 'html';
			$(options.target)[fn](data).each(oldSuccess, arguments);
		});
	}
	else if (options.success) {
		callbacks.push(options.success);
	}

	options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
		var context = options.context || options;   // jQuery 1.4+ supports scope context 
		for (var i=0, max=callbacks.length; i < max; i++) {
			callbacks[i].apply(context, [data, status, xhr || $form, $form]);
		}
	};

	// are there files to upload?
	var fileInputs = $('input:file', this).length > 0;
	var mp = 'multipart/form-data';
	var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);

	// options.iframe allows user to force iframe mode
	// 06-NOV-09: now defaulting to iframe mode if file input is detected
   if (options.iframe !== false && (fileInputs || options.iframe || multipart)) {
	   // hack to fix Safari hang (thanks to Tim Molendijk for this)
	   // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
	   if (options.closeKeepAlive) {
		   $.get(options.closeKeepAlive, fileUpload);
		}
	   else {
		   fileUpload();
		}
   }
   else {
	   $.ajax(options);
   }

	// fire 'notify' event
	this.trigger('form-submit-notify', [this, options]);
	return this;


	// private function for handling file uploads (hat tip to YAHOO!)
	function fileUpload() {
		var form = $form[0];

		if ($(':input[name=submit],:input[id=submit]', form).length) {
			// if there is an input with a name or id of 'submit' then we won't be
			// able to invoke the submit fn on the form (at least not x-browser)
			alert('Error: Form elements must not have name or id of "submit".');
			return;
		}
		
		var s = $.extend(true, {}, $.ajaxSettings, options);
		s.context = s.context || s;
		var id = 'jqFormIO' + (new Date().getTime()), fn = '_'+id;
		window[fn] = function() {
			var f = $io.data('form-plugin-onload');
			if (f) {
				f();
				window[fn] = undefined;
				try { delete window[fn]; } catch(e){}
			}
		}
		var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ s.iframeSrc +'" onload="window[\'_\'+this.id]()" />');
		var io = $io[0];

		$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

		var xhr = { // mock object
			aborted: 0,
			responseText: null,
			responseXML: null,
			status: 0,
			statusText: 'n/a',
			getAllResponseHeaders: function() {},
			getResponseHeader: function() {},
			setRequestHeader: function() {},
			abort: function() {
				this.aborted = 1;
				$io.attr('src', s.iframeSrc); // abort op in progress
			}
		};

		var g = s.global;
		// trigger ajax global events so that activity/block indicators work like normal
		if (g && ! $.active++) {
			$.event.trigger("ajaxStart");
		}
		if (g) {
			$.event.trigger("ajaxSend", [xhr, s]);
		}

		if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
			if (s.global) { 
				$.active--;
			}
			return;
		}
		if (xhr.aborted) {
			return;
		}

		var cbInvoked = false;
		var timedOut = 0;

		// add submitting element to data if we know it
		var sub = form.clk;
		if (sub) {
			var n = sub.name;
			if (n && !sub.disabled) {
				s.extraData = s.extraData || {};
				s.extraData[n] = sub.value;
				if (sub.type == "image") {
					s.extraData[n+'.x'] = form.clk_x;
					s.extraData[n+'.y'] = form.clk_y;
				}
			}
		}

		// take a breath so that pending repaints get some cpu time before the upload starts
		function doSubmit() {
			// make sure form attrs are set
			var t = $form.attr('target'), a = $form.attr('action');

			// update form attrs in IE friendly way
			form.setAttribute('target',id);
			if (form.getAttribute('method') != 'POST') {
				form.setAttribute('method', 'POST');
			}
			if (form.getAttribute('action') != s.url) {
				form.setAttribute('action', s.url);
			}

			// ie borks in some cases when setting encoding
			if (! s.skipEncodingOverride) {
				$form.attr({
					encoding: 'multipart/form-data',
					enctype:  'multipart/form-data'
				});
			}

			// support timout
			if (s.timeout) {
				setTimeout(function() { timedOut = true; cb(); }, s.timeout);
			}

			// add "extra" data to form if provided in options
			var extraInputs = [];
			try {
				if (s.extraData) {
					for (var n in s.extraData) {
						extraInputs.push(
							$('<input type="hidden" name="'+n+'" value="'+s.extraData[n]+'" />')
								.appendTo(form)[0]);
					}
				}

				// add iframe to doc and submit the form
				$io.appendTo('body');
				$io.data('form-plugin-onload', cb);
				form.submit();
			}
			finally {
				// reset attrs and remove "extra" input elements
				form.setAttribute('action',a);
				if(t) {
					form.setAttribute('target', t);
				} else {
					$form.removeAttr('target');
				}
				$(extraInputs).remove();
			}
		}

		if (s.forceSync) {
			doSubmit();
		}
		else {
			setTimeout(doSubmit, 10); // this lets dom updates render
		}
	
		var data, doc, domCheckCount = 50;

		function cb() {
			if (cbInvoked) {
				return;
			}

			$io.removeData('form-plugin-onload');
			
			var ok = true;
			try {
				if (timedOut) {
					throw 'timeout';
				}
				// extract the server response from the iframe
				doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
				
				var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
				log('isXml='+isXml);
				if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) {
					if (--domCheckCount) {
						// in some browsers (Opera) the iframe DOM is not always traversable when
						// the onload callback fires, so we loop a bit to accommodate
						log('requeing onLoad callback, DOM not available');
						setTimeout(cb, 250);
						return;
					}
					// let this fall through because server response could be an empty document
					//log('Could not access iframe DOM after mutiple tries.');
					//throw 'DOMException: not available';
				}

				//log('response detected');
				cbInvoked = true;
				xhr.responseText = doc.documentElement ? doc.documentElement.innerHTML : null; 
				xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
				xhr.getResponseHeader = function(header){
					var headers = {'content-type': s.dataType};
					return headers[header];
				};

				var scr = /(json|script)/.test(s.dataType);
				if (scr || s.textarea) {
					// see if user embedded response in textarea
					var ta = doc.getElementsByTagName('textarea')[0];
					if (ta) {
						xhr.responseText = ta.value;
					}
					else if (scr) {
						// account for browsers injecting pre around json response
						var pre = doc.getElementsByTagName('pre')[0];
						if (pre) {
							xhr.responseText = pre.innerHTML;
						}
					}			  
				}
				else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
					xhr.responseXML = toXml(xhr.responseText);
				}
				data = $.httpData(xhr, s.dataType);
			}
			catch(e){
				log('error caught:',e);
				ok = false;
				xhr.error = e;
				$.handleError(s, xhr, 'error', e);
			}

			// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
			if (ok) {
				s.success.call(s.context, data, 'success', xhr);
				if (g) {
					$.event.trigger("ajaxSuccess", [xhr, s]);
				}
			}
			if (g) {
				$.event.trigger("ajaxComplete", [xhr, s]);
			}
			if (g && ! --$.active) {
				$.event.trigger("ajaxStop");
			}
			if (s.complete) {
				s.complete.call(s.context, xhr, ok ? 'success' : 'error');
			}

			// clean up
			setTimeout(function() {
				$io.removeData('form-plugin-onload');
				$io.remove();
				xhr.responseXML = null;
			}, 100);
		}

		function toXml(s, doc) {
			if (window.ActiveXObject) {
				doc = new ActiveXObject('Microsoft.XMLDOM');
				doc.async = 'false';
				doc.loadXML(s);
			}
			else {
				doc = (new DOMParser()).parseFromString(s, 'text/xml');
			}
			return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
		}
	}
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *	is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *	used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */
$.fn.ajaxForm = function(options) {
	// in jQuery 1.3+ we can fix mistakes with the ready state
	if (this.length === 0) {
		var o = { s: this.selector, c: this.context };
		if (!$.isReady && o.s) {
			log('DOM not ready, queuing ajaxForm');
			$(function() {
				$(o.s,o.c).ajaxForm(options);
			});
			return this;
		}
		// is your DOM ready?  http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
		log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
		return this;
	}
	
	return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) {
		if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
			e.preventDefault();
			$(this).ajaxSubmit(options);
		}
	}).bind('click.form-plugin', function(e) {
		var target = e.target;
		var $el = $(target);
		if (!($el.is(":submit,input:image"))) {
			// is this a child element of the submit el?  (ex: a span within a button)
			var t = $el.closest(':submit');
			if (t.length == 0) {
				return;
			}
			target = t[0];
		}
		var form = this;
		form.clk = target;
		if (target.type == 'image') {
			if (e.offsetX != undefined) {
				form.clk_x = e.offsetX;
				form.clk_y = e.offsetY;
			} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
				var offset = $el.offset();
				form.clk_x = e.pageX - offset.left;
				form.clk_y = e.pageY - offset.top;
			} else {
				form.clk_x = e.pageX - target.offsetLeft;
				form.clk_y = e.pageY - target.offsetTop;
			}
		}
		// clear form vars
		setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
	});
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
	return this.unbind('submit.form-plugin click.form-plugin');
};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
	var a = [];
	if (this.length === 0) {
		return a;
	}

	var form = this[0];
	var els = semantic ? form.getElementsByTagName('*') : form.elements;
	if (!els) {
		return a;
	}
	
	var i,j,n,v,el;
	for(i=0, max=els.length; i < max; i++) {
		el = els[i];
		n = el.name;
		if (!n) {
			continue;
		}

		if (semantic && form.clk && el.type == "image") {
			// handle image inputs on the fly when semantic == true
			if(!el.disabled && form.clk == el) {
				a.push({name: n, value: $(el).val()});
				a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
			}
			continue;
		}

		v = $.fieldValue(el, true);
		if (v && v.constructor == Array) {
			for(j=0, jmax=v.length; j < jmax; j++) {
				a.push({name: n, value: v[j]});
			}
		}
		else if (v !== null && typeof v != 'undefined') {
			a.push({name: n, value: v});
		}
	}

	if (!semantic && form.clk) {
		// input type=='image' are not found in elements array! handle it here
		var $input = $(form.clk), input = $input[0];
		n = input.name;
		if (n && !input.disabled && input.type == 'image') {
			a.push({name: n, value: $input.val()});
			a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
		}
	}
	return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
	//hand off to jQuery.param for proper encoding
	return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
	var a = [];
	this.each(function() {
		var n = this.name;
		if (!n) {
			return;
		}
		var v = $.fieldValue(this, successful);
		if (v && v.constructor == Array) {
			for (var i=0,max=v.length; i < max; i++) {
				a.push({name: n, value: v[i]});
			}
		}
		else if (v !== null && typeof v != 'undefined') {
			a.push({name: this.name, value: v});
		}
	});
	//hand off to jQuery.param for proper encoding
	return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *	  <input name="A" type="text" />
 *	  <input name="A" type="text" />
 *	  <input name="B" type="checkbox" value="B1" />
 *	  <input name="B" type="checkbox" value="B2"/>
 *	  <input name="C" type="radio" value="C1" />
 *	  <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *	   array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
	for (var val=[], i=0, max=this.length; i < max; i++) {
		var el = this[i];
		var v = $.fieldValue(el, successful);
		if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
			continue;
		}
		v.constructor == Array ? $.merge(val, v) : val.push(v);
	}
	return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
	var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
	if (successful === undefined) {
		successful = true;
	}

	if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
		(t == 'checkbox' || t == 'radio') && !el.checked ||
		(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
		tag == 'select' && el.selectedIndex == -1)) {
			return null;
	}

	if (tag == 'select') {
		var index = el.selectedIndex;
		if (index < 0) {
			return null;
		}
		var a = [], ops = el.options;
		var one = (t == 'select-one');
		var max = (one ? index+1 : ops.length);
		for(var i=(one ? index : 0); i < max; i++) {
			var op = ops[i];
			if (op.selected) {
				var v = op.value;
				if (!v) { // extra pain for IE...
					v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
				}
				if (one) {
					return v;
				}
				a.push(v);
			}
		}
		return a;
	}
	return $(el).val();
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
	return this.each(function() {
		$('input,select,textarea', this).clearFields();
	});
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
	return this.each(function() {
		var t = this.type, tag = this.tagName.toLowerCase();
		if (t == 'text' || t == 'password' || tag == 'textarea') {
			this.value = '';
		}
		else if (t == 'checkbox' || t == 'radio') {
			this.checked = false;
		}
		else if (tag == 'select') {
			this.selectedIndex = -1;
		}
	});
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
	return this.each(function() {
		// guard against an input with the name of 'reset'
		// note that IE reports the reset function as an 'object'
		if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
			this.reset();
		}
	});
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) {
	if (b === undefined) {
		b = true;
	}
	return this.each(function() {
		this.disabled = !b;
	});
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
	if (select === undefined) {
		select = true;
	}
	return this.each(function() {
		var t = this.type;
		if (t == 'checkbox' || t == 'radio') {
			this.checked = select;
		}
		else if (this.tagName.toLowerCase() == 'option') {
			var $sel = $(this).parent('select');
			if (select && $sel[0] && $sel[0].type == 'select-one') {
				// deselect all other options
				$sel.find('option').selected(false);
			}
			this.selected = select;
		}
	});
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
	if ($.fn.ajaxSubmit.debug) {
		var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
		if (window.console && window.console.log) {
			window.console.log(msg);
		}
		else if (window.opera && window.opera.postError) {
			window.opera.postError(msg);
		}
	}
};

})(jQuery);
;
var MattelPluck = function() {
	var requests = [];
	var resultsCallback = null;

	var pluckUrl = Drupal.settings.mattel_pluck.url;
	var baseUrl = Drupal.settings.mattel_pluck.base_url;
	var filePath = Drupal.settings.mattel_pluck.file_path;

	function bind() {
	}

	function queue(request) {
		requests.push(request);
	}

	function setResultsCallback(callback) {
		resultsCallback = callback;
	}

	function send() {
		PluckSDK.SendRequests(requests, resultsCallback);
		resultsCallback = processResults;
		requests = [];
	}

	function processResults(responses) {
		if (window.console) window.console.dir(responses);
	}

	function getImageUrl(pluckImageUrl, preset) {
		var pluckBaseUrl = 'http://' + pluckUrl + '/';
		var baseUrlLength = pluckBaseUrl.length;
		var imagePath = pluckImageUrl.substr(baseUrlLength);

		if (typeof(preset) == 'undefined') {
			return baseUrl + '/' + filePath + '/pluck/photo/' + imagePath;
		}
		else {
			return baseUrl + '/' + filePath + '/imagecache/' + preset + '/pluck/photo/' + imagePath;
		}
	}

	resultsCallback = processResults;

	return {
		'bind':                bind,
		'queue':               queue,
		'setResultsCallback' : setResultsCallback,
		'send':                send,
		'getImageUrl':         getImageUrl
	};
}

Drupal.behaviors.mattel_pluck = function(context) {
	if (typeof(PluckSDK) != 'undefined' && typeof(mattel_pluck) == 'undefined') {
		mattel_pluck = new MattelPluck();
	}

	if (typeof(mattel_pluck) != 'undefined') {
		mattel_pluck.bind(context);
	}
};
;
/*
 * Shadowbox.js, version 3.0.3
 * http://shadowbox-js.com/
 *
 * Copyright 2007-2010, Michael J. I. Jackson
 * Date: 2010-04-06 04:42:15 +0000
 */
(function(au,k){var Q={version:"3.0.3"};var J=navigator.userAgent.toLowerCase();if(J.indexOf("windows")>-1||J.indexOf("win32")>-1){Q.isWindows=true}else{if(J.indexOf("macintosh")>-1||J.indexOf("mac os x")>-1){Q.isMac=true}else{if(J.indexOf("linux")>-1){Q.isLinux=true}}}Q.isIE=J.indexOf("msie")>-1;Q.isIE6=J.indexOf("msie 6")>-1;Q.isIE7=J.indexOf("msie 7")>-1;Q.isGecko=J.indexOf("gecko")>-1&&J.indexOf("safari")==-1;Q.isWebKit=J.indexOf("applewebkit/")>-1;var ab=/#(.+)$/,af=/^(light|shadow)box\[(.*?)\]/i,az=/\s*([a-z_]*?)\s*=\s*(.+)\s*/,f=/[0-9a-z]+$/i,aD=/(.+\/)shadowbox\.js/i;var A=false,a=false,l={},z=0,R,ap;Q.current=-1;Q.dimensions=null;Q.ease=function(K){return 1+Math.pow(K-1,3)};Q.errorInfo={fla:{name:"Flash",url:"http://www.adobe.com/products/flashplayer/"},qt:{name:"QuickTime",url:"http://www.apple.com/quicktime/download/"},wmp:{name:"Windows Media Player",url:"http://www.microsoft.com/windows/windowsmedia/"},f4m:{name:"Flip4Mac",url:"http://www.flip4mac.com/wmv_download.htm"}};Q.gallery=[];Q.onReady=aj;Q.path=null;Q.player=null;Q.playerId="sb-player";Q.options={animate:true,animateFade:true,autoplayMovies:true,continuous:false,enableKeys:true,flashParams:{bgcolor:"#000000",allowfullscreen:true},flashVars:{},flashVersion:"9.0.115",handleOversize:"resize",handleUnsupported:"link",onChange:aj,onClose:aj,onFinish:aj,onOpen:aj,showMovieControls:true,skipSetup:false,slideshowDelay:0,viewportPadding:20};Q.getCurrent=function(){return Q.current>-1?Q.gallery[Q.current]:null};Q.hasNext=function(){return Q.gallery.length>1&&(Q.current!=Q.gallery.length-1||Q.options.continuous)};Q.isOpen=function(){return A};Q.isPaused=function(){return ap=="pause"};Q.applyOptions=function(K){l=aC({},Q.options);aC(Q.options,K)};Q.revertOptions=function(){aC(Q.options,l)};Q.init=function(aG,aJ){if(a){return}a=true;if(Q.skin.options){aC(Q.options,Q.skin.options)}if(aG){aC(Q.options,aG)}if(!Q.path){var aI,S=document.getElementsByTagName("script");for(var aH=0,K=S.length;aH<K;++aH){aI=aD.exec(S[aH].src);if(aI){Q.path=aI[1];break}}}if(aJ){Q.onReady=aJ}P()};Q.open=function(S){if(A){return}var K=Q.makeGallery(S);Q.gallery=K[0];Q.current=K[1];S=Q.getCurrent();if(S==null){return}Q.applyOptions(S.options||{});G();if(Q.gallery.length){S=Q.getCurrent();if(Q.options.onOpen(S)===false){return}A=true;Q.skin.onOpen(S,c)}};Q.close=function(){if(!A){return}A=false;if(Q.player){Q.player.remove();Q.player=null}if(typeof ap=="number"){clearTimeout(ap);ap=null}z=0;aq(false);Q.options.onClose(Q.getCurrent());Q.skin.onClose();Q.revertOptions()};Q.play=function(){if(!Q.hasNext()){return}if(!z){z=Q.options.slideshowDelay*1000}if(z){R=aw();ap=setTimeout(function(){z=R=0;Q.next()},z);if(Q.skin.onPlay){Q.skin.onPlay()}}};Q.pause=function(){if(typeof ap!="number"){return}z=Math.max(0,z-(aw()-R));if(z){clearTimeout(ap);ap="pause";if(Q.skin.onPause){Q.skin.onPause()}}};Q.change=function(K){if(!(K in Q.gallery)){if(Q.options.continuous){K=(K<0?Q.gallery.length+K:0);if(!(K in Q.gallery)){return}}else{return}}Q.current=K;if(typeof ap=="number"){clearTimeout(ap);ap=null;z=R=0}Q.options.onChange(Q.getCurrent());c(true)};Q.next=function(){Q.change(Q.current+1)};Q.previous=function(){Q.change(Q.current-1)};Q.setDimensions=function(aS,aJ,aQ,aR,aI,K,aO,aL){var aN=aS,aH=aJ;var aM=2*aO+aI;if(aS+aM>aQ){aS=aQ-aM}var aG=2*aO+K;if(aJ+aG>aR){aJ=aR-aG}var S=(aN-aS)/aN,aP=(aH-aJ)/aH,aK=(S>0||aP>0);if(aL&&aK){if(S>aP){aJ=Math.round((aH/aN)*aS)}else{if(aP>S){aS=Math.round((aN/aH)*aJ)}}}Q.dimensions={height:aS+aI,width:aJ+K,innerHeight:aS,innerWidth:aJ,top:Math.floor((aQ-(aS+aM))/2+aO),left:Math.floor((aR-(aJ+aG))/2+aO),oversized:aK};return Q.dimensions};Q.makeGallery=function(aI){var K=[],aH=-1;if(typeof aI=="string"){aI=[aI]}if(typeof aI.length=="number"){aF(aI,function(aK,aL){if(aL.content){K[aK]=aL}else{K[aK]={content:aL}}});aH=0}else{if(aI.tagName){var S=Q.getCache(aI);aI=S?S:Q.makeObject(aI)}if(aI.gallery){K=[];var aJ;for(var aG in Q.cache){aJ=Q.cache[aG];if(aJ.gallery&&aJ.gallery==aI.gallery){if(aH==-1&&aJ.content==aI.content){aH=K.length}K.push(aJ)}}if(aH==-1){K.unshift(aI);aH=0}}else{K=[aI];aH=0}}aF(K,function(aK,aL){K[aK]=aC({},aL)});return[K,aH]};Q.makeObject=function(aH,aG){var aI={content:aH.href,title:aH.getAttribute("title")||"",link:aH};if(aG){aG=aC({},aG);aF(["player","title","height","width","gallery"],function(aJ,aK){if(typeof aG[aK]!="undefined"){aI[aK]=aG[aK];delete aG[aK]}});aI.options=aG}else{aI.options={}}if(!aI.player){aI.player=Q.getPlayer(aI.content)}var K=aH.getAttribute("rel");if(K){var S=K.match(af);if(S){aI.gallery=escape(S[2])}aF(K.split(";"),function(aJ,aK){S=aK.match(az);if(S){aI[S[1]]=S[2]}})}return aI};Q.getPlayer=function(aG){if(aG.indexOf("#")>-1&&aG.indexOf(document.location.href)==0){return"inline"}var aH=aG.indexOf("?");if(aH>-1){aG=aG.substring(0,aH)}var S,K=aG.match(f);if(K){S=K[0].toLowerCase()}if(S){if(Q.img&&Q.img.ext.indexOf(S)>-1){return"img"}if(Q.swf&&Q.swf.ext.indexOf(S)>-1){return"swf"}if(Q.flv&&Q.flv.ext.indexOf(S)>-1){return"flv"}if(Q.qt&&Q.qt.ext.indexOf(S)>-1){if(Q.wmp&&Q.wmp.ext.indexOf(S)>-1){return"qtwmp"}else{return"qt"}}if(Q.wmp&&Q.wmp.ext.indexOf(S)>-1){return"wmp"}}return"iframe"};function G(){var aH=Q.errorInfo,aI=Q.plugins,aK,aL,aO,aG,aN,S,aM,K;for(var aJ=0;aJ<Q.gallery.length;++aJ){aK=Q.gallery[aJ];aL=false;aO=null;switch(aK.player){case"flv":case"swf":if(!aI.fla){aO="fla"}break;case"qt":if(!aI.qt){aO="qt"}break;case"wmp":if(Q.isMac){if(aI.qt&&aI.f4m){aK.player="qt"}else{aO="qtf4m"}}else{if(!aI.wmp){aO="wmp"}}break;case"qtwmp":if(aI.qt){aK.player="qt"}else{if(aI.wmp){aK.player="wmp"}else{aO="qtwmp"}}break}if(aO){if(Q.options.handleUnsupported=="link"){switch(aO){case"qtf4m":aN="shared";S=[aH.qt.url,aH.qt.name,aH.f4m.url,aH.f4m.name];break;case"qtwmp":aN="either";S=[aH.qt.url,aH.qt.name,aH.wmp.url,aH.wmp.name];break;default:aN="single";S=[aH[aO].url,aH[aO].name]}aK.player="html";aK.content='<div class="sb-message">'+s(Q.lang.errors[aN],S)+"</div>"}else{aL=true}}else{if(aK.player=="inline"){aG=ab.exec(aK.content);if(aG){aM=ad(aG[1]);if(aM){aK.content=aM.innerHTML}else{aL=true}}else{aL=true}}else{if(aK.player=="swf"||aK.player=="flv"){K=(aK.options&&aK.options.flashVersion)||Q.options.flashVersion;if(Q.flash&&!Q.flash.hasFlashPlayerVersion(K)){aK.width=310;aK.height=177}}}}if(aL){Q.gallery.splice(aJ,1);if(aJ<Q.current){--Q.current}else{if(aJ==Q.current){Q.current=aJ>0?aJ-1:aJ}}--aJ}}}function aq(K){if(!Q.options.enableKeys){return}(K?F:M)(document,"keydown",an)}function an(aG){if(aG.metaKey||aG.shiftKey||aG.altKey||aG.ctrlKey){return}var S=v(aG),K;switch(S){case 81:case 88:case 27:K=Q.close;break;case 37:K=Q.previous;break;case 39:K=Q.next;break;case 32:K=typeof ap=="number"?Q.pause:Q.play;break}if(K){n(aG);K()}}function c(aK){aq(false);var aJ=Q.getCurrent();var aG=(aJ.player=="inline"?"html":aJ.player);if(typeof Q[aG]!="function"){throw"unknown player "+aG}if(aK){Q.player.remove();Q.revertOptions();Q.applyOptions(aJ.options||{})}Q.player=new Q[aG](aJ,Q.playerId);if(Q.gallery.length>1){var aH=Q.gallery[Q.current+1]||Q.gallery[0];if(aH.player=="img"){var S=new Image();S.src=aH.content}var aI=Q.gallery[Q.current-1]||Q.gallery[Q.gallery.length-1];if(aI.player=="img"){var K=new Image();K.src=aI.content}}Q.skin.onLoad(aK,W)}function W(){if(!A){return}if(typeof Q.player.ready!="undefined"){var K=setInterval(function(){if(A){if(Q.player.ready){clearInterval(K);K=null;Q.skin.onReady(e)}}else{clearInterval(K);K=null}},10)}else{Q.skin.onReady(e)}}function e(){if(!A){return}Q.player.append(Q.skin.body,Q.dimensions);Q.skin.onShow(I)}function I(){if(!A){return}if(Q.player.onLoad){Q.player.onLoad()}Q.options.onFinish(Q.getCurrent());if(!Q.isPaused()){Q.play()}aq(true)}if(!Array.prototype.indexOf){Array.prototype.indexOf=function(S,aG){var K=this.length>>>0;aG=aG||0;if(aG<0){aG+=K}for(;aG<K;++aG){if(aG in this&&this[aG]===S){return aG}}return -1}}function aw(){return(new Date).getTime()}function aC(K,aG){for(var S in aG){K[S]=aG[S]}return K}function aF(aH,aI){var S=0,K=aH.length;for(var aG=aH[0];S<K&&aI.call(aG,S,aG)!==false;aG=aH[++S]){}}function s(S,K){return S.replace(/\{(\w+?)\}/g,function(aG,aH){return K[aH]})}function aj(){}function ad(K){return document.getElementById(K)}function C(K){K.parentNode.removeChild(K)}var h=true,x=true;function d(){var K=document.body,S=document.createElement("div");h=typeof S.style.opacity==="string";S.style.position="fixed";S.style.margin=0;S.style.top="20px";K.appendChild(S,K.firstChild);x=S.offsetTop==20;K.removeChild(S)}Q.getStyle=(function(){var K=/opacity=([^)]*)/,S=document.defaultView&&document.defaultView.getComputedStyle;return function(aJ,aI){var aH;if(!h&&aI=="opacity"&&aJ.currentStyle){aH=K.test(aJ.currentStyle.filter||"")?(parseFloat(RegExp.$1)/100)+"":"";return aH===""?"1":aH}if(S){var aG=S(aJ,null);if(aG){aH=aG[aI]}if(aI=="opacity"&&aH==""){aH="1"}}else{aH=aJ.currentStyle[aI]}return aH}})();Q.appendHTML=function(aG,S){if(aG.insertAdjacentHTML){aG.insertAdjacentHTML("BeforeEnd",S)}else{if(aG.lastChild){var K=aG.ownerDocument.createRange();K.setStartAfter(aG.lastChild);var aH=K.createContextualFragment(S);aG.appendChild(aH)}else{aG.innerHTML=S}}};Q.getWindowSize=function(K){if(document.compatMode==="CSS1Compat"){return document.documentElement["client"+K]}return document.body["client"+K]};Q.setOpacity=function(aG,K){var S=aG.style;if(h){S.opacity=(K==1?"":K)}else{S.zoom=1;if(K==1){if(typeof S.filter=="string"&&(/alpha/i).test(S.filter)){S.filter=S.filter.replace(/\s*[\w\.]*alpha\([^\)]*\);?/gi,"")}}else{S.filter=(S.filter||"").replace(/\s*[\w\.]*alpha\([^\)]*\)/gi,"")+" alpha(opacity="+(K*100)+")"}}};Q.clearOpacity=function(K){Q.setOpacity(K,1)};function o(S){var K=S.target?S.target:S.srcElement;return K.nodeType==3?K.parentNode:K}function V(S){var K=S.pageX||(S.clientX+(document.documentElement.scrollLeft||document.body.scrollLeft)),aG=S.pageY||(S.clientY+(document.documentElement.scrollTop||document.body.scrollTop));return[K,aG]}function n(K){K.preventDefault()}function v(K){return K.which?K.which:K.keyCode}function F(aH,aG,S){if(aH.addEventListener){aH.addEventListener(aG,S,false)}else{if(aH.nodeType===3||aH.nodeType===8){return}if(aH.setInterval&&(aH!==au&&!aH.frameElement)){aH=au}if(!S.__guid){S.__guid=F.guid++}if(!aH.events){aH.events={}}var K=aH.events[aG];if(!K){K=aH.events[aG]={};if(aH["on"+aG]){K[0]=aH["on"+aG]}}K[S.__guid]=S;aH["on"+aG]=F.handleEvent}}F.guid=1;F.handleEvent=function(aH){var K=true;aH=aH||F.fixEvent(((this.ownerDocument||this.document||this).parentWindow||au).event);var S=this.events[aH.type];for(var aG in S){this.__handleEvent=S[aG];if(this.__handleEvent(aH)===false){K=false}}return K};F.preventDefault=function(){this.returnValue=false};F.stopPropagation=function(){this.cancelBubble=true};F.fixEvent=function(K){K.preventDefault=F.preventDefault;K.stopPropagation=F.stopPropagation;return K};function M(aG,S,K){if(aG.removeEventListener){aG.removeEventListener(S,K,false)}else{if(aG.events&&aG.events[S]){delete aG.events[S][K.__guid]}}}var y=false,al;if(document.addEventListener){al=function(){document.removeEventListener("DOMContentLoaded",al,false);Q.load()}}else{if(document.attachEvent){al=function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",al);Q.load()}}}}function g(){if(y){return}try{document.documentElement.doScroll("left")}catch(K){setTimeout(g,1);return}Q.load()}function P(){if(document.readyState==="complete"){return Q.load()}if(document.addEventListener){document.addEventListener("DOMContentLoaded",al,false);au.addEventListener("load",Q.load,false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",al);au.attachEvent("onload",Q.load);var K=false;try{K=au.frameElement===null}catch(S){}if(document.documentElement.doScroll&&K){g()}}}}Q.load=function(){if(y){return}if(!document.body){return setTimeout(Q.load,13)}y=true;d();Q.onReady();if(!Q.options.skipSetup){Q.setup()}Q.skin.init()};Q.plugins={};if(navigator.plugins&&navigator.plugins.length){var w=[];aF(navigator.plugins,function(K,S){w.push(S.name)});w=w.join(",");var ai=w.indexOf("Flip4Mac")>-1;Q.plugins={fla:w.indexOf("Shockwave Flash")>-1,qt:w.indexOf("QuickTime")>-1,wmp:!ai&&w.indexOf("Windows Media")>-1,f4m:ai}}else{var p=function(K){var S;try{S=new ActiveXObject(K)}catch(aG){}return !!S};Q.plugins={fla:p("ShockwaveFlash.ShockwaveFlash"),qt:p("QuickTime.QuickTime"),wmp:p("wmplayer.ocx"),f4m:false}}var X=/^(light|shadow)box/i,am="shadowboxCacheKey",b=1;Q.cache={};Q.select=function(S){var aG=[];if(!S){var K;aF(document.getElementsByTagName("a"),function(aJ,aK){K=aK.getAttribute("rel");if(K&&X.test(K)){aG.push(aK)}})}else{var aI=S.length;if(aI){if(typeof S=="string"){if(Q.find){aG=Q.find(S)}}else{if(aI==2&&typeof S[0]=="string"&&S[1].nodeType){if(Q.find){aG=Q.find(S[0],S[1])}}else{for(var aH=0;aH<aI;++aH){aG[aH]=S[aH]}}}}else{aG.push(S)}}return aG};Q.setup=function(K,S){aF(Q.select(K),function(aG,aH){Q.addCache(aH,S)})};Q.teardown=function(K){aF(Q.select(K),function(S,aG){Q.removeCache(aG)})};Q.addCache=function(aG,K){var S=aG[am];if(S==k){S=b++;aG[am]=S;F(aG,"click",u)}Q.cache[S]=Q.makeObject(aG,K)};Q.removeCache=function(K){M(K,"click",u);delete Q.cache[K[am]];K[am]=null};Q.getCache=function(S){var K=S[am];return(K in Q.cache&&Q.cache[K])};Q.clearCache=function(){for(var K in Q.cache){Q.removeCache(Q.cache[K].link)}Q.cache={}};function u(K){Q.open(this);if(Q.gallery.length){n(K)}}
/*
 * Sizzle CSS Selector Engine - v1.0
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 *
 * Modified for inclusion in Shadowbox.js
 */
Q.find=(function(){var aP=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,aQ=0,aS=Object.prototype.toString,aK=false,aJ=true;[0,0].sort(function(){aJ=false;return 0});var aG=function(a1,aW,a4,a5){a4=a4||[];var a7=aW=aW||document;if(aW.nodeType!==1&&aW.nodeType!==9){return[]}if(!a1||typeof a1!=="string"){return a4}var a2=[],aY,a9,bc,aX,a0=true,aZ=aH(aW),a6=a1;while((aP.exec(""),aY=aP.exec(a6))!==null){a6=aY[3];a2.push(aY[1]);if(aY[2]){aX=aY[3];break}}if(a2.length>1&&aL.exec(a1)){if(a2.length===2&&aM.relative[a2[0]]){a9=aT(a2[0]+a2[1],aW)}else{a9=aM.relative[a2[0]]?[aW]:aG(a2.shift(),aW);while(a2.length){a1=a2.shift();if(aM.relative[a1]){a1+=a2.shift()}a9=aT(a1,a9)}}}else{if(!a5&&a2.length>1&&aW.nodeType===9&&!aZ&&aM.match.ID.test(a2[0])&&!aM.match.ID.test(a2[a2.length-1])){var a8=aG.find(a2.shift(),aW,aZ);aW=a8.expr?aG.filter(a8.expr,a8.set)[0]:a8.set[0]}if(aW){var a8=a5?{expr:a2.pop(),set:aO(a5)}:aG.find(a2.pop(),a2.length===1&&(a2[0]==="~"||a2[0]==="+")&&aW.parentNode?aW.parentNode:aW,aZ);a9=a8.expr?aG.filter(a8.expr,a8.set):a8.set;if(a2.length>0){bc=aO(a9)}else{a0=false}while(a2.length){var bb=a2.pop(),ba=bb;if(!aM.relative[bb]){bb=""}else{ba=a2.pop()}if(ba==null){ba=aW}aM.relative[bb](bc,ba,aZ)}}else{bc=a2=[]}}if(!bc){bc=a9}if(!bc){throw"Syntax error, unrecognized expression: "+(bb||a1)}if(aS.call(bc)==="[object Array]"){if(!a0){a4.push.apply(a4,bc)}else{if(aW&&aW.nodeType===1){for(var a3=0;bc[a3]!=null;a3++){if(bc[a3]&&(bc[a3]===true||bc[a3].nodeType===1&&aN(aW,bc[a3]))){a4.push(a9[a3])}}}else{for(var a3=0;bc[a3]!=null;a3++){if(bc[a3]&&bc[a3].nodeType===1){a4.push(a9[a3])}}}}}else{aO(bc,a4)}if(aX){aG(aX,a7,a4,a5);aG.uniqueSort(a4)}return a4};aG.uniqueSort=function(aX){if(aR){aK=aJ;aX.sort(aR);if(aK){for(var aW=1;aW<aX.length;aW++){if(aX[aW]===aX[aW-1]){aX.splice(aW--,1)}}}}return aX};aG.matches=function(aW,aX){return aG(aW,null,null,aX)};aG.find=function(a3,aW,a4){var a2,a0;if(!a3){return[]}for(var aZ=0,aY=aM.order.length;aZ<aY;aZ++){var a1=aM.order[aZ],a0;if((a0=aM.leftMatch[a1].exec(a3))){var aX=a0[1];a0.splice(1,1);if(aX.substr(aX.length-1)!=="\\"){a0[1]=(a0[1]||"").replace(/\\/g,"");a2=aM.find[a1](a0,aW,a4);if(a2!=null){a3=a3.replace(aM.match[a1],"");break}}}}if(!a2){a2=aW.getElementsByTagName("*")}return{set:a2,expr:a3}};aG.filter=function(a6,a5,a9,aZ){var aY=a6,bb=[],a3=a5,a1,aW,a2=a5&&a5[0]&&aH(a5[0]);while(a6&&a5.length){for(var a4 in aM.filter){if((a1=aM.match[a4].exec(a6))!=null){var aX=aM.filter[a4],ba,a8;aW=false;if(a3===bb){bb=[]}if(aM.preFilter[a4]){a1=aM.preFilter[a4](a1,a3,a9,bb,aZ,a2);if(!a1){aW=ba=true}else{if(a1===true){continue}}}if(a1){for(var a0=0;(a8=a3[a0])!=null;a0++){if(a8){ba=aX(a8,a1,a0,a3);var a7=aZ^!!ba;if(a9&&ba!=null){if(a7){aW=true}else{a3[a0]=false}}else{if(a7){bb.push(a8);aW=true}}}}}if(ba!==k){if(!a9){a3=bb}a6=a6.replace(aM.match[a4],"");if(!aW){return[]}break}}}if(a6===aY){if(aW==null){throw"Syntax error, unrecognized expression: "+a6}else{break}}aY=a6}return a3};var aM=aG.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\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(aW){return aW.getAttribute("href")}},relative:{"+":function(a2,aX){var aZ=typeof aX==="string",a1=aZ&&!/\W/.test(aX),a3=aZ&&!a1;if(a1){aX=aX.toLowerCase()}for(var aY=0,aW=a2.length,a0;aY<aW;aY++){if((a0=a2[aY])){while((a0=a0.previousSibling)&&a0.nodeType!==1){}a2[aY]=a3||a0&&a0.nodeName.toLowerCase()===aX?a0||false:a0===aX}}if(a3){aG.filter(aX,a2,true)}},">":function(a2,aX){var a0=typeof aX==="string";if(a0&&!/\W/.test(aX)){aX=aX.toLowerCase();for(var aY=0,aW=a2.length;aY<aW;aY++){var a1=a2[aY];if(a1){var aZ=a1.parentNode;a2[aY]=aZ.nodeName.toLowerCase()===aX?aZ:false}}}else{for(var aY=0,aW=a2.length;aY<aW;aY++){var a1=a2[aY];if(a1){a2[aY]=a0?a1.parentNode:a1.parentNode===aX}}if(a0){aG.filter(aX,a2,true)}}},"":function(aZ,aX,a1){var aY=aQ++,aW=aU;if(typeof aX==="string"&&!/\W/.test(aX)){var a0=aX=aX.toLowerCase();aW=K}aW("parentNode",aX,aY,aZ,a0,a1)},"~":function(aZ,aX,a1){var aY=aQ++,aW=aU;if(typeof aX==="string"&&!/\W/.test(aX)){var a0=aX=aX.toLowerCase();aW=K}aW("previousSibling",aX,aY,aZ,a0,a1)}},find:{ID:function(aX,aY,aZ){if(typeof aY.getElementById!=="undefined"&&!aZ){var aW=aY.getElementById(aX[1]);return aW?[aW]:[]}},NAME:function(aY,a1){if(typeof a1.getElementsByName!=="undefined"){var aX=[],a0=a1.getElementsByName(aY[1]);for(var aZ=0,aW=a0.length;aZ<aW;aZ++){if(a0[aZ].getAttribute("name")===aY[1]){aX.push(a0[aZ])}}return aX.length===0?null:aX}},TAG:function(aW,aX){return aX.getElementsByTagName(aW[1])}},preFilter:{CLASS:function(aZ,aX,aY,aW,a2,a3){aZ=" "+aZ[1].replace(/\\/g,"")+" ";if(a3){return aZ}for(var a0=0,a1;(a1=aX[a0])!=null;a0++){if(a1){if(a2^(a1.className&&(" "+a1.className+" ").replace(/[\t\n]/g," ").indexOf(aZ)>=0)){if(!aY){aW.push(a1)}}else{if(aY){aX[a0]=false}}}}return false},ID:function(aW){return aW[1].replace(/\\/g,"")},TAG:function(aX,aW){return aX[1].toLowerCase()},CHILD:function(aW){if(aW[1]==="nth"){var aX=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(aW[2]==="even"&&"2n"||aW[2]==="odd"&&"2n+1"||!/\D/.test(aW[2])&&"0n+"+aW[2]||aW[2]);aW[2]=(aX[1]+(aX[2]||1))-0;aW[3]=aX[3]-0}aW[0]=aQ++;return aW},ATTR:function(a0,aX,aY,aW,a1,a2){var aZ=a0[1].replace(/\\/g,"");if(!a2&&aM.attrMap[aZ]){a0[1]=aM.attrMap[aZ]}if(a0[2]==="~="){a0[4]=" "+a0[4]+" "}return a0},PSEUDO:function(a0,aX,aY,aW,a1){if(a0[1]==="not"){if((aP.exec(a0[3])||"").length>1||/^\w/.test(a0[3])){a0[3]=aG(a0[3],null,null,aX)}else{var aZ=aG.filter(a0[3],aX,aY,true^a1);if(!aY){aW.push.apply(aW,aZ)}return false}}else{if(aM.match.POS.test(a0[0])||aM.match.CHILD.test(a0[0])){return true}}return a0},POS:function(aW){aW.unshift(true);return aW}},filters:{enabled:function(aW){return aW.disabled===false&&aW.type!=="hidden"},disabled:function(aW){return aW.disabled===true},checked:function(aW){return aW.checked===true},selected:function(aW){aW.parentNode.selectedIndex;return aW.selected===true},parent:function(aW){return !!aW.firstChild},empty:function(aW){return !aW.firstChild},has:function(aY,aX,aW){return !!aG(aW[3],aY).length},header:function(aW){return/h\d/i.test(aW.nodeName)},text:function(aW){return"text"===aW.type},radio:function(aW){return"radio"===aW.type},checkbox:function(aW){return"checkbox"===aW.type},file:function(aW){return"file"===aW.type},password:function(aW){return"password"===aW.type},submit:function(aW){return"submit"===aW.type},image:function(aW){return"image"===aW.type},reset:function(aW){return"reset"===aW.type},button:function(aW){return"button"===aW.type||aW.nodeName.toLowerCase()==="button"},input:function(aW){return/input|select|textarea|button/i.test(aW.nodeName)}},setFilters:{first:function(aX,aW){return aW===0},last:function(aY,aX,aW,aZ){return aX===aZ.length-1},even:function(aX,aW){return aW%2===0},odd:function(aX,aW){return aW%2===1},lt:function(aY,aX,aW){return aX<aW[3]-0},gt:function(aY,aX,aW){return aX>aW[3]-0},nth:function(aY,aX,aW){return aW[3]-0===aX},eq:function(aY,aX,aW){return aW[3]-0===aX}},filter:{PSEUDO:function(a2,aY,aZ,a3){var aX=aY[1],a0=aM.filters[aX];if(a0){return a0(a2,aZ,aY,a3)}else{if(aX==="contains"){return(a2.textContent||a2.innerText||S([a2])||"").indexOf(aY[3])>=0}else{if(aX==="not"){var a1=aY[3];for(var aZ=0,aW=a1.length;aZ<aW;aZ++){if(a1[aZ]===a2){return false}}return true}else{throw"Syntax error, unrecognized expression: "+aX}}}},CHILD:function(aW,aZ){var a2=aZ[1],aX=aW;switch(a2){case"only":case"first":while((aX=aX.previousSibling)){if(aX.nodeType===1){return false}}if(a2==="first"){return true}aX=aW;case"last":while((aX=aX.nextSibling)){if(aX.nodeType===1){return false}}return true;case"nth":var aY=aZ[2],a5=aZ[3];if(aY===1&&a5===0){return true}var a1=aZ[0],a4=aW.parentNode;if(a4&&(a4.sizcache!==a1||!aW.nodeIndex)){var a0=0;for(aX=a4.firstChild;aX;aX=aX.nextSibling){if(aX.nodeType===1){aX.nodeIndex=++a0}}a4.sizcache=a1}var a3=aW.nodeIndex-a5;if(aY===0){return a3===0}else{return(a3%aY===0&&a3/aY>=0)}}},ID:function(aX,aW){return aX.nodeType===1&&aX.getAttribute("id")===aW},TAG:function(aX,aW){return(aW==="*"&&aX.nodeType===1)||aX.nodeName.toLowerCase()===aW},CLASS:function(aX,aW){return(" "+(aX.className||aX.getAttribute("class"))+" ").indexOf(aW)>-1},ATTR:function(a1,aZ){var aY=aZ[1],aW=aM.attrHandle[aY]?aM.attrHandle[aY](a1):a1[aY]!=null?a1[aY]:a1.getAttribute(aY),a2=aW+"",a0=aZ[2],aX=aZ[4];return aW==null?a0==="!=":a0==="="?a2===aX:a0==="*="?a2.indexOf(aX)>=0:a0==="~="?(" "+a2+" ").indexOf(aX)>=0:!aX?a2&&aW!==false:a0==="!="?a2!==aX:a0==="^="?a2.indexOf(aX)===0:a0==="$="?a2.substr(a2.length-aX.length)===aX:a0==="|="?a2===aX||a2.substr(0,aX.length+1)===aX+"-":false},POS:function(a0,aX,aY,a1){var aW=aX[2],aZ=aM.setFilters[aW];if(aZ){return aZ(a0,aY,aX,a1)}}}};var aL=aM.match.POS;for(var aI in aM.match){aM.match[aI]=new RegExp(aM.match[aI].source+/(?![^\[]*\])(?![^\(]*\))/.source);aM.leftMatch[aI]=new RegExp(/(^(?:.|\r|\n)*?)/.source+aM.match[aI].source)}var aO=function(aX,aW){aX=Array.prototype.slice.call(aX,0);if(aW){aW.push.apply(aW,aX);return aW}return aX};try{Array.prototype.slice.call(document.documentElement.childNodes,0)}catch(aV){aO=function(a0,aZ){var aX=aZ||[];if(aS.call(a0)==="[object Array]"){Array.prototype.push.apply(aX,a0)}else{if(typeof a0.length==="number"){for(var aY=0,aW=a0.length;aY<aW;aY++){aX.push(a0[aY])}}else{for(var aY=0;a0[aY];aY++){aX.push(a0[aY])}}}return aX}}var aR;if(document.documentElement.compareDocumentPosition){aR=function(aX,aW){if(!aX.compareDocumentPosition||!aW.compareDocumentPosition){if(aX==aW){aK=true}return aX.compareDocumentPosition?-1:1}var aY=aX.compareDocumentPosition(aW)&4?-1:aX===aW?0:1;if(aY===0){aK=true}return aY}}else{if("sourceIndex" in document.documentElement){aR=function(aX,aW){if(!aX.sourceIndex||!aW.sourceIndex){if(aX==aW){aK=true}return aX.sourceIndex?-1:1}var aY=aX.sourceIndex-aW.sourceIndex;if(aY===0){aK=true}return aY}}else{if(document.createRange){aR=function(aZ,aX){if(!aZ.ownerDocument||!aX.ownerDocument){if(aZ==aX){aK=true}return aZ.ownerDocument?-1:1}var aY=aZ.ownerDocument.createRange(),aW=aX.ownerDocument.createRange();aY.setStart(aZ,0);aY.setEnd(aZ,0);aW.setStart(aX,0);aW.setEnd(aX,0);var a0=aY.compareBoundaryPoints(Range.START_TO_END,aW);if(a0===0){aK=true}return a0}}}}function S(aW){var aX="",aZ;for(var aY=0;aW[aY];aY++){aZ=aW[aY];if(aZ.nodeType===3||aZ.nodeType===4){aX+=aZ.nodeValue}else{if(aZ.nodeType!==8){aX+=S(aZ.childNodes)}}}return aX}(function(){var aX=document.createElement("div"),aY="script"+(new Date).getTime();aX.innerHTML="<a name='"+aY+"'/>";var aW=document.documentElement;aW.insertBefore(aX,aW.firstChild);if(document.getElementById(aY)){aM.find.ID=function(a0,a1,a2){if(typeof a1.getElementById!=="undefined"&&!a2){var aZ=a1.getElementById(a0[1]);return aZ?aZ.id===a0[1]||typeof aZ.getAttributeNode!=="undefined"&&aZ.getAttributeNode("id").nodeValue===a0[1]?[aZ]:k:[]}};aM.filter.ID=function(a1,aZ){var a0=typeof a1.getAttributeNode!=="undefined"&&a1.getAttributeNode("id");return a1.nodeType===1&&a0&&a0.nodeValue===aZ}}aW.removeChild(aX);aW=aX=null})();(function(){var aW=document.createElement("div");aW.appendChild(document.createComment(""));if(aW.getElementsByTagName("*").length>0){aM.find.TAG=function(aX,a1){var a0=a1.getElementsByTagName(aX[1]);if(aX[1]==="*"){var aZ=[];for(var aY=0;a0[aY];aY++){if(a0[aY].nodeType===1){aZ.push(a0[aY])}}a0=aZ}return a0}}aW.innerHTML="<a href='#'></a>";if(aW.firstChild&&typeof aW.firstChild.getAttribute!=="undefined"&&aW.firstChild.getAttribute("href")!=="#"){aM.attrHandle.href=function(aX){return aX.getAttribute("href",2)}}aW=null})();if(document.querySelectorAll){(function(){var aW=aG,aY=document.createElement("div");aY.innerHTML="<p class='TEST'></p>";if(aY.querySelectorAll&&aY.querySelectorAll(".TEST").length===0){return}aG=function(a2,a1,aZ,a0){a1=a1||document;if(!a0&&a1.nodeType===9&&!aH(a1)){try{return aO(a1.querySelectorAll(a2),aZ)}catch(a3){}}return aW(a2,a1,aZ,a0)};for(var aX in aW){aG[aX]=aW[aX]}aY=null})()}(function(){var aW=document.createElement("div");aW.innerHTML="<div class='test e'></div><div class='test'></div>";if(!aW.getElementsByClassName||aW.getElementsByClassName("e").length===0){return}aW.lastChild.className="e";if(aW.getElementsByClassName("e").length===1){return}aM.order.splice(1,0,"CLASS");aM.find.CLASS=function(aX,aY,aZ){if(typeof aY.getElementsByClassName!=="undefined"&&!aZ){return aY.getElementsByClassName(aX[1])}};aW=null})();function K(aX,a2,a1,a5,a3,a4){for(var aZ=0,aY=a5.length;aZ<aY;aZ++){var aW=a5[aZ];if(aW){aW=aW[aX];var a0=false;while(aW){if(aW.sizcache===a1){a0=a5[aW.sizset];break}if(aW.nodeType===1&&!a4){aW.sizcache=a1;aW.sizset=aZ}if(aW.nodeName.toLowerCase()===a2){a0=aW;break}aW=aW[aX]}a5[aZ]=a0}}}function aU(aX,a2,a1,a5,a3,a4){for(var aZ=0,aY=a5.length;aZ<aY;aZ++){var aW=a5[aZ];if(aW){aW=aW[aX];var a0=false;while(aW){if(aW.sizcache===a1){a0=a5[aW.sizset];break}if(aW.nodeType===1){if(!a4){aW.sizcache=a1;aW.sizset=aZ}if(typeof a2!=="string"){if(aW===a2){a0=true;break}}else{if(aG.filter(a2,[aW]).length>0){a0=aW;break}}}aW=aW[aX]}a5[aZ]=a0}}}var aN=document.compareDocumentPosition?function(aX,aW){return aX.compareDocumentPosition(aW)&16}:function(aX,aW){return aX!==aW&&(aX.contains?aX.contains(aW):true)};var aH=function(aW){var aX=(aW?aW.ownerDocument||aW:0).documentElement;return aX?aX.nodeName!=="HTML":false};var aT=function(aW,a3){var aZ=[],a0="",a1,aY=a3.nodeType?[a3]:a3;while((a1=aM.match.PSEUDO.exec(aW))){a0+=a1[0];aW=aW.replace(aM.match.PSEUDO,"")}aW=aM.relative[aW]?aW+"*":aW;for(var a2=0,aX=aY.length;a2<aX;a2++){aG(aW,aY[a2],aZ)}return aG.filter(a0,aZ)};return aG})();Q.lang={code:"en",of:"of",loading:"loading",cancel:"Cancel",next:"Next",previous:"Previous",play:"Play",pause:"Pause",close:"Close",errors:{single:'You must install the <a href="{0}">{1}</a> browser plugin to view this content.',shared:'You must install both the <a href="{0}">{1}</a> and <a href="{2}">{3}</a> browser plugins to view this content.',either:'You must install either the <a href="{0}">{1}</a> or the <a href="{2}">{3}</a> browser plugin to view this content.'}};var D,at="sb-drag-proxy",E,j,ag;function ax(){E={x:0,y:0,startX:null,startY:null}}function aA(){var K=Q.dimensions;aC(j.style,{height:K.innerHeight+"px",width:K.innerWidth+"px"})}function O(){ax();var K=["position:absolute","cursor:"+(Q.isGecko?"-moz-grab":"move"),"background-color:"+(Q.isIE?"#fff;filter:alpha(opacity=0)":"transparent")].join(";");Q.appendHTML(Q.skin.body,'<div id="'+at+'" style="'+K+'"></div>');j=ad(at);aA();F(j,"mousedown",L)}function B(){if(j){M(j,"mousedown",L);C(j);j=null}ag=null}function L(S){n(S);var K=V(S);E.startX=K[0];E.startY=K[1];ag=ad(Q.player.id);F(document,"mousemove",H);F(document,"mouseup",i);if(Q.isGecko){j.style.cursor="-moz-grabbing"}}function H(aI){var K=Q.player,aJ=Q.dimensions,aH=V(aI);var aG=aH[0]-E.startX;E.startX+=aG;E.x=Math.max(Math.min(0,E.x+aG),aJ.innerWidth-K.width);var S=aH[1]-E.startY;E.startY+=S;E.y=Math.max(Math.min(0,E.y+S),aJ.innerHeight-K.height);aC(ag.style,{left:E.x+"px",top:E.y+"px"})}function i(){M(document,"mousemove",H);M(document,"mouseup",i);if(Q.isGecko){j.style.cursor="-moz-grab"}}Q.img=function(S,aG){this.obj=S;this.id=aG;this.ready=false;var K=this;D=new Image();D.onload=function(){K.height=S.height?parseInt(S.height,10):D.height;K.width=S.width?parseInt(S.width,10):D.width;K.ready=true;D.onload=null;D=null};D.src=S.content};Q.img.ext=["bmp","gif","jpg","jpeg","png"];Q.img.prototype={append:function(S,aI){var aG=document.createElement("img");aG.id=this.id;aG.src=this.obj.content;aG.style.position="absolute";var K,aH;if(aI.oversized&&Q.options.handleOversize=="resize"){K=aI.innerHeight;aH=aI.innerWidth}else{K=this.height;aH=this.width}aG.setAttribute("height",K);aG.setAttribute("width",aH);S.appendChild(aG)},remove:function(){var K=ad(this.id);if(K){C(K)}B();if(D){D.onload=null;D=null}},onLoad:function(){var K=Q.dimensions;if(K.oversized&&Q.options.handleOversize=="drag"){O()}},onWindowResize:function(){var aH=Q.dimensions;switch(Q.options.handleOversize){case"resize":var K=ad(this.id);K.height=aH.innerHeight;K.width=aH.innerWidth;break;case"drag":if(ag){var aG=parseInt(Q.getStyle(ag,"top")),S=parseInt(Q.getStyle(ag,"left"));if(aG+this.height<aH.innerHeight){ag.style.top=aH.innerHeight-this.height+"px"}if(S+this.width<aH.innerWidth){ag.style.left=aH.innerWidth-this.width+"px"}aA()}break}}};var ao=false,Y=[],q=["sb-nav-close","sb-nav-next","sb-nav-play","sb-nav-pause","sb-nav-previous"],aa,ae,Z,m=true;function N(aG,aQ,aN,aL,aR){var K=(aQ=="opacity"),aM=K?Q.setOpacity:function(aS,aT){aS.style[aQ]=""+aT+"px"};if(aL==0||(!K&&!Q.options.animate)||(K&&!Q.options.animateFade)){aM(aG,aN);if(aR){aR()}return}var aO=parseFloat(Q.getStyle(aG,aQ))||0;var aP=aN-aO;if(aP==0){if(aR){aR()}return}aL*=1000;var aH=aw(),aK=Q.ease,aJ=aH+aL,aI;var S=setInterval(function(){aI=aw();if(aI>=aJ){clearInterval(S);S=null;aM(aG,aN);if(aR){aR()}}else{aM(aG,aO+aK((aI-aH)/aL)*aP)}},10)}function aB(){aa.style.height=Q.getWindowSize("Height")+"px";aa.style.width=Q.getWindowSize("Width")+"px"}function aE(){aa.style.top=document.documentElement.scrollTop+"px";aa.style.left=document.documentElement.scrollLeft+"px"}function ay(K){if(K){aF(Y,function(S,aG){aG[0].style.visibility=aG[1]||""})}else{Y=[];aF(Q.options.troubleElements,function(aG,S){aF(document.getElementsByTagName(S),function(aH,aI){Y.push([aI,aI.style.visibility]);aI.style.visibility="hidden"})})}}function r(aG,K){var S=ad("sb-nav-"+aG);if(S){S.style.display=K?"":"none"}}function ah(K,aJ){var aI=ad("sb-loading"),aG=Q.getCurrent().player,aH=(aG=="img"||aG=="html");if(K){Q.setOpacity(aI,0);aI.style.display="block";var S=function(){Q.clearOpacity(aI);if(aJ){aJ()}};if(aH){N(aI,"opacity",1,Q.options.fadeDuration,S)}else{S()}}else{var S=function(){aI.style.display="none";Q.clearOpacity(aI);if(aJ){aJ()}};if(aH){N(aI,"opacity",0,Q.options.fadeDuration,S)}else{S()}}}function t(aO){var aJ=Q.getCurrent();ad("sb-title-inner").innerHTML=aJ.title||"";var aP,aL,S,aQ,aM;if(Q.options.displayNav){aP=true;var aN=Q.gallery.length;if(aN>1){if(Q.options.continuous){aL=aM=true}else{aL=(aN-1)>Q.current;aM=Q.current>0}}if(Q.options.slideshowDelay>0&&Q.hasNext()){aQ=!Q.isPaused();S=!aQ}}else{aP=aL=S=aQ=aM=false}r("close",aP);r("next",aL);r("play",S);r("pause",aQ);r("previous",aM);var K="";if(Q.options.displayCounter&&Q.gallery.length>1){var aN=Q.gallery.length;if(Q.options.counterType=="skip"){var aI=0,aH=aN,aG=parseInt(Q.options.counterLimit)||0;if(aG<aN&&aG>2){var aK=Math.floor(aG/2);aI=Q.current-aK;if(aI<0){aI+=aN}aH=Q.current+(aG-aK);if(aH>aN){aH-=aN}}while(aI!=aH){if(aI==aN){aI=0}K+='<a onclick="Shadowbox.change('+aI+');"';if(aI==Q.current){K+=' class="sb-counter-current"'}K+=">"+(++aI)+"</a>"}}else{K=[Q.current+1,Q.lang.of,aN].join(" ")}}ad("sb-counter").innerHTML=K;aO()}function U(aH){var K=ad("sb-title-inner"),aG=ad("sb-info-inner"),S=0.35;K.style.visibility=aG.style.visibility="";if(K.innerHTML!=""){N(K,"marginTop",0,S)}N(aG,"marginTop",0,S,aH)}function av(aG,aM){var aK=ad("sb-title"),K=ad("sb-info"),aH=aK.offsetHeight,aI=K.offsetHeight,aJ=ad("sb-title-inner"),aL=ad("sb-info-inner"),S=(aG?0.35:0);N(aJ,"marginTop",aH,S);N(aL,"marginTop",aI*-1,S,function(){aJ.style.visibility=aL.style.visibility="hidden";aM()})}function ac(K,aH,S,aJ){var aI=ad("sb-wrapper-inner"),aG=(S?Q.options.resizeDuration:0);N(Z,"top",aH,aG);N(aI,"height",K,aG,aJ)}function ar(K,aH,S,aI){var aG=(S?Q.options.resizeDuration:0);N(Z,"left",aH,aG);N(Z,"width",K,aG,aI)}function ak(aM,aG){var aI=ad("sb-body-inner"),aM=parseInt(aM),aG=parseInt(aG),S=Z.offsetHeight-aI.offsetHeight,K=Z.offsetWidth-aI.offsetWidth,aK=ae.offsetHeight,aL=ae.offsetWidth,aJ=parseInt(Q.options.viewportPadding)||20,aH=(Q.player&&Q.options.handleOversize!="drag");return Q.setDimensions(aM,aG,aK,aL,S,K,aJ,aH)}var T={};T.markup='<div id="sb-container"><div id="sb-overlay"></div><div id="sb-wrapper"><div id="sb-title"><div id="sb-title-inner"></div></div><div id="sb-wrapper-inner"><div id="sb-body"><div id="sb-body-inner"></div><div id="sb-loading"><div id="sb-loading-inner"><span>{loading}</span></div></div></div></div><div id="sb-info"><div id="sb-info-inner"><div id="sb-counter"></div><div id="sb-nav"><a id="sb-nav-close" title="{close}" onclick="Shadowbox.close()"></a><a id="sb-nav-next" title="{next}" onclick="Shadowbox.next()"></a><a id="sb-nav-play" title="{play}" onclick="Shadowbox.play()"></a><a id="sb-nav-pause" title="{pause}" onclick="Shadowbox.pause()"></a><a id="sb-nav-previous" title="{previous}" onclick="Shadowbox.previous()"></a></div></div></div></div></div>';T.options={animSequence:"sync",counterLimit:10,counterType:"default",displayCounter:true,displayNav:true,fadeDuration:0.35,initialHeight:160,initialWidth:320,modal:false,overlayColor:"#000",overlayOpacity:0.5,resizeDuration:0.35,showOverlay:true,troubleElements:["select","object","embed","canvas"]};T.init=function(){Q.appendHTML(document.body,s(T.markup,Q.lang));T.body=ad("sb-body-inner");aa=ad("sb-container");ae=ad("sb-overlay");Z=ad("sb-wrapper");if(!x){aa.style.position="absolute"}if(!h){var aG,K,S=/url\("(.*\.png)"\)/;aF(q,function(aI,aJ){aG=ad(aJ);if(aG){K=Q.getStyle(aG,"backgroundImage").match(S);if(K){aG.style.backgroundImage="none";aG.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,src="+K[1]+",sizingMethod=scale);"}}})}var aH;F(au,"resize",function(){if(aH){clearTimeout(aH);aH=null}if(A){aH=setTimeout(T.onWindowResize,10)}})};T.onOpen=function(K,aG){m=false;aa.style.display="block";aB();var S=ak(Q.options.initialHeight,Q.options.initialWidth);ac(S.innerHeight,S.top);ar(S.width,S.left);if(Q.options.showOverlay){ae.style.backgroundColor=Q.options.overlayColor;Q.setOpacity(ae,0);if(!Q.options.modal){F(ae,"click",Q.close)}ao=true}if(!x){aE();F(au,"scroll",aE)}ay();aa.style.visibility="visible";if(ao){N(ae,"opacity",Q.options.overlayOpacity,Q.options.fadeDuration,aG)}else{aG()}};T.onLoad=function(S,K){ah(true);while(T.body.firstChild){C(T.body.firstChild)}av(S,function(){if(!A){return}if(!S){Z.style.visibility="visible"}t(K)})};T.onReady=function(aH){if(!A){return}var S=Q.player,aG=ak(S.height,S.width);var K=function(){U(aH)};switch(Q.options.animSequence){case"hw":ac(aG.innerHeight,aG.top,true,function(){ar(aG.width,aG.left,true,K)});break;case"wh":ar(aG.width,aG.left,true,function(){ac(aG.innerHeight,aG.top,true,K)});break;default:ar(aG.width,aG.left,true);ac(aG.innerHeight,aG.top,true,K)}};T.onShow=function(K){ah(false,K);m=true};T.onClose=function(){if(!x){M(au,"scroll",aE)}M(ae,"click",Q.close);Z.style.visibility="hidden";var K=function(){aa.style.visibility="hidden";aa.style.display="none";ay(true)};if(ao){N(ae,"opacity",0,Q.options.fadeDuration,K)}else{K()}};T.onPlay=function(){r("play",false);r("pause",true)};T.onPause=function(){r("pause",false);r("play",true)};T.onWindowResize=function(){if(!m){return}aB();var K=Q.player,S=ak(K.height,K.width);ar(S.width,S.left);ac(S.innerHeight,S.top);if(K.onWindowResize){K.onWindowResize()}};Q.skin=T;au.Shadowbox=Q})(window);;
// $Id: shadowbox_auto.js,v 1.1.4.4.2.4.2.1 2010/04/03 05:53:55 nicholasalipaz Exp $

Drupal.behaviors.shadowbox = function (context) {
  var settings = Drupal.settings.shadowbox;
  if (settings.auto_enable_all_images == 1) {
    $("a[href$='jpg'], a[href$='png'], a[href$='gif'], a[href$='jpeg'], a[href$='bmp'], a[href$='JPG'], a[href$='PNG'], a[href$='GIF'], a[href$='JPEG'], a[href$='BMP']").each(function() {
      if (settings.auto_gallery == 1) {
        $(this).attr('rel', 'shadowbox[gallery]');
      }
      else {
        $(this).attr('rel', 'shadowbox');
      };
    });
  };
  Shadowbox.setup();
};
;
/*	SWFObject v2.2 <http://code.google.com/p/swfobject/> 
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();;
Debug = false;

function oc(a){
  var o = {};
  for(var i=0;i<a.length;i++){
    o[a[i]]='';
  }
  return o;
}

// What : BFC, LOGGED
function isCurrentUser(what) {
  what = what.toLowerCase();
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) === " ") c = c.substring(1, c.length);
    var eqIndex = c.indexOf("=");
    if (eqIndex > 0) {
      var name = c.substring(0, eqIndex), value = c.substring(eqIndex + 1);
      if (name.toLowerCase() === 'at') {
        value = unescape(value);
        value = value.split('&');
        if( (what === "bfc") && ("bfc=1" in oc(value)) ){
          return true;
        } else if(what === "logged"){
          return true;
        }
      }
    }
  }
  return false;
}

Printer = function(){
  var datenow = new Date();
  var User_BFC = isCurrentUser("BFC");
  var User_Logged = isCurrentUser("LOGGED");
  var site_prefix = Drupal.settings.mattel_pluck.content_prefix;
  
  // Collectors
  var recentActivity = [];  
  var HideAfter = 20;
  var photosCollection = {};
  
  // Whats Hot
  var whatshot = {};
  whatshot.comments = [];
  whatshot.forums = [];
  whatshot.photos = [];

	// Dollicious
	var mostPhotos = {};
  
  /**************/
  /*  Templates */
  /**************/
  /* Collectors */
  var commentTemplate = "<div class='buzz-entry comment'>" +
    "<div class='entry-left'>" +
      "<div class='user-avatar'>@user_avatar</a></div>" +
    "</div>" +
    "<div class='entry-right'>" +
      "<div class='@member_status member-status'>" +
        "<div class='update'>" + Drupal.t('<a class="user_name" href="@user_url">@name</a> commented on  <a href="@item_url">@title</a>') + ":</div>" +
        "<div class='buzz-content'><p>@content</p></div>" +
        "<div class='created'>@date</div>" +
      "</div>" +
    "</div>" +
  "</div>";
  
  var commentPhotoTemplate = "<div class='buzz-entry comment-photo'>" +
    "<div class='entry-left'>" +
      "<div class='user-avatar'>@user_avatar</a></div>" +
    "</div>" +
    "<div class='entry-right'>" +
      "<div class='@member_status member-status'>" +
        "<div class='update'>" + Drupal.t('<a class="user_name" href="@user_url">@name</a> commented on an image <a href="@item_url">@title</a>') + ":</div>" +
        "<div class='photo'><a href='@item_url'><img src='@thumb_src'/></a></div>" +
        "<div class='buzz-content'><p>@content</p></div>" +
        "<div class='created'>@date</div>" +
      "</div>" +
    "</div>" +
  "</div>";  
  
  var tidbitTemplate = "<div class='buzz-entry tidbit'>" +
    "<div class='entry-left'>" +
      "<div class='user-avatar'>@user_avatar</div>" +
    "</div>" +
    "<div class='entry-right'>" +
      "<div class='@member_status member-status'>" +
        "<div class='update'>" + Drupal.t('<a class="user_name" href="@user_url">@name</a> commented on <a href="@item_url">@title</a>:</div>') + 
        "<div class='buzz-content'><p>@content</p></div>" +
        "<div class='created'>@date</div>" +
      "</div>" +
    "</div>" +
  "</div>";
  
  var forumspostTemplate = "<div class='buzz-entry forums_post bfc-only'>" +
    "<div class='entry-left'>" +
      "<div class='user-avatar'>@user_avatar</div>" +
    "</div>" +
    "<div class='entry-right'>" +
      "<div class='@member_status member-status'>"; 
  if(User_BFC){
    forumspostTemplate += "<div class='update'>" + Drupal.t('<a class="user_name" href="@user_url">@name</a> posted a new topic in the  <a href="@item_url">Barbie Fan Club Bulletin Board: @title</a>') + "</div>";
    forumspostTemplate += "<div class='buzz-content'><p>@content</p></div>";
  } else {
    forumspostTemplate += "<div class='update'>" + Drupal.t('<a class="user_name" href="@user_url">@name</a> posted a new topic in the Barbie Fan Club Bulletin Board: @title') + "</div>";
  }
  if(!User_BFC){
    forumspostTemplate += '<div class="bfc-action"><a href="' + Drupal.settings.mattel_pluck.bfc_card_path + '"><span>' + Drupal.t('Become a barbie fan club member to see exclusive content.') + '</span></a></div>';
  }
  forumspostTemplate +=  "<div class='created'>@date</div></div>" +
    "</div>" +
  "</div>";
  
  var photoUserTemplate = "<div class='buzz-entry photo'>" +
    "<div class='entry-left'>" +
      "<div class='user-avatar'>@user_avatar</div>" +
    "</div>" +
    "<div class='entry-right'>" +
      "<div class='@member_status member-status'>" +
        "<div class='update'>@message</div>" +
        "<div class='buzz-content'>@content</div>" +
        "<div class='created'>@date</div>" +
      "</div>" +
    "</div>" +
  "</div>";
  
  var favDollTemplate = "<div class='buzz-entry fav-doll'>" +
    "<div class='entry-left'>" +
      "<div class='user-avatar'>@user_avatar</div>" +
    "</div>" +
    "<div class='entry-right'>" +
      "<div class='@member_status member-status'>" +
        "<div class='update'>" +
        Drupal.t('<a class="user_name" href="@user_url">@name</a>\'s  all time favorite Barbie: ') +
        "<a href='@item_url'>@title</a>." +
        "</div>" +
        "<div class='buzz-content'><a href='@item_url' class='fav-doll-thumb'><img src='@img_url' /></a><div class='doll-title'></div><p>@content</p></div>" +
        "<div class='created'>@date</div>" +
      "</div>" +
    "</div>" +
  "</div>";
  
  
  /* Tidbit block in dolls/accessory page */
  var tidbitBlockTemplate = '<div id="@MinCommentKey" class="waiting tidbit_item"><div class="tidbit_item_wrapper"><div class="tidbit_item_content"><div class="tidbit-left">' +
    '<div class="tidbit_content">@body</div>' +
    '<div class="author">' +
      '<span>' + Drupal.t('According to ')  + '</span><a class="user_name" href="@user_url">@name</a>' +
    '</div>' +
    '<div class="abuse_action">'+
      '<a class="comment abuselink" href="#" rel="#@CommentKey">' + Drupal.t('Flag as inappropriate') + '</a>' +
    '</div>'+
    '</div><div class="tidbit-right">';
  if(User_Logged){
    tidbitBlockTemplate += '<div class="tidbit-right"><div class="tidbit_rating">' +
      '<p>' + Drupal.t('Do you like this?') + '<p>' +
      '<a class="thump_up" rel="@articleId" title="I like this!" href="#@CommentKey">@score</a>' +
      '</div></div>';
  } else {
    tidbitBlockTemplate += '<div class="tidbit_rating">' +
      '<p>' + Drupal.t('<span onClick="$(\'#header a.loginlink\').click(); return false;" style="cursor:pointer;border-bottom:1px solid #EC4399;">Login</span> to rate this comment!') + '<p>' +
      '<span class="thump_up" title="People like this!">@score</span>' +
      '</div>';
  }
  tidbitBlockTemplate += '</div></div></div></div>';
  
  
  // User overlay Template
  userOverlayTemplate = '<div class="user_overlay pluck-user-mp-wrap hasCorners" style="display:none;">' +
      '<div class="pluck-user-mp-sidebar" style="display: block;">' +
        '<div class="pluck-user-mp-avatar-seethrough">' +
            '<a href="@user_url"><img class="pluck-user-mp-avatarimg" alt="" src="@user_avatar"></a>' +
        '</div>' +
    '</div>' +    
    '<div class="pluck-user-mp-content" style="display: block;">' +
        '<h4 class="pluck-user-mp-username">' +
          '<a href="@user_url"><span class="pluck-user-mp-username-value">@name</span></a>' +
        '</h4>' +
        '@extrainfos' +
        '<div class="pluck-user-mp-activity-area">' +
          '<p style="display:inline;" class="pluck-user-mp-info">@user_bio</p>' +
        '</div>' +
      '</div>' +
    '</div>';
  
  /*************************/
  /*  Print Item Functions */
  /*************************/  
  function printUserAvatar(user){
    var lien, overlay, extrainfos = [], bio = '';
    if( (typeof(user.AboutMe) != "undefined") && (user.AboutMe != '') ) {
      bio = '<span class="pluck-user-mp-sub-head">Bio: </span><span class="pluck-user-mp-text pluck-user-mp-bio">' + limitStr(user.AboutMe, 160) + '</span>';
    }
    if( (typeof(user.Location) != "undefined") && (user.Location != "") ) { extrainfos.push(user.Location); }
    if( (typeof(user.Age) != "undefined") && (user.Age != "") ) { extrainfos.push(user.Age); }
    if( (typeof(user.Sex) != "undefined") && (user.Sex != "") ) { extrainfos.push(user.Sex); }
    extrainfos = '<p class="pluck-user-mp-asl">' + extrainfos.join(' | ') + '</p>';
    
    overlay = fillTemplate(userOverlayTemplate,
        {
          '@name' : user.DisplayName,
          '@user_avatar' : user.AvatarPhotoUrl,
          '@user_url' : user.PersonaUrl,   
          '@user_bio' : bio,
          '@extrainfos' : extrainfos 
        }
    );
    lien = '<a class="avatar_img" href="' + user.PersonaUrl + '"><img src="'+ user.AvatarPhotoUrl + '"/></a>';
    return '<div class="persona_overlay">' + overlay + lien + '</div>';
  }
  
  function printComment(object){
    return fillTemplate(commentTemplate,    
        {
          '@name' : object.Owner.DisplayName,
          '@content' : limitStr(object.Body, 300),
          '@date' : printPostedTime(object.PostedAtTime),
          '@user_avatar' : printUserAvatar(object.Owner),
          '@user_url' : object.Owner.PersonaUrl,
          '@title' : object.Parent.Title.replace('| Barbie Collector', ''),
          '@item_url' : object.Url,
          '@member_status' : BFC_Member_Status(object.Owner)     
        }
      );
  }
  
  function printCommentPhoto(object){
    var photoInCollectionUrl, re = new RegExp('[0-9]+');
    var id = re.exec(object.Owner.UserKey.Key);    
    photoInCollectionUrl = '/user/' + id + '/photos/' + object.CommentedOnKey.Key + '#user-photo';

    return fillTemplate(commentPhotoTemplate,    
        {
          '@name' : object.Owner.DisplayName,
          '@content' : limitStr(object.Body, 300),
          '@date' : printPostedTime(object.PostedAtTime),
          '@user_avatar' : printUserAvatar(object.Owner),
          '@user_url' : object.Owner.PersonaUrl,
          '@title' : object.Parent.Title.replace('| Barbie Collector', ''),
          '@thumb_src' : object.Url,
          '@member_status' : BFC_Member_Status(object.Owner),
          '@item_url' : photoInCollectionUrl       
        }
      );
  }  
  
  function printTidbit(object){
    return fillTemplate(tidbitTemplate,    
        {
          '@name' : object.Owner.DisplayName,
          '@content' : limitStr(object.Body, 300),
          '@date' : printPostedTime(object.PostedAtTime),
          '@user_avatar' : printUserAvatar(object.Owner),
          '@user_url' : object.Owner.PersonaUrl,
          '@title' : object.Parent.Title.replace('| Barbie Collector', ''),
          '@item_url' : object.Url,
          '@member_status' : BFC_Member_Status(object.Owner)
        }
      );
  }
  
  function printForumsMsg(object){
    return fillTemplate(forumspostTemplate,    
        {
          '@name' : object.Owner.DisplayName,
          '@content' : limitStr(object.Body, 300),
          '@date' : printPostedTime(object.FirstPostDate),
          '@user_avatar' : printUserAvatar(object.Owner),
          '@user_url' : object.Owner.PersonaUrl,
          '@title' : object.Title,
          '@item_url' : object.Url.replace('directforums', 'forums'),
          '@member_status' : BFC_Member_Status(object.Owner)
        }
      );
  }  
  
  
  function printFavDoll(object){
    var buzzinfos;
    try{
      buzzinfos = YAHOO.lang.JSON.parse(object.Content);
    } catch(e){
      try{
        buzzinfos = jQuery.parseJSON(object.Content);
      } catch(er){}
    }
    if(typeof(buzzinfos) == 'object'){
      return fillTemplate(favDollTemplate,    
          {
            '@name' : object.Owner.DisplayName,
            '@content' : buzzinfos.doll_text,
            '@img_url' : buzzinfos.doll_img,
            '@date' : printPostedTime(object.SortTime),
            '@user_avatar' : printUserAvatar(object.Owner),
            '@user_url' : object.Owner.PersonaUrl,
            '@title' : buzzinfos.doll_title,
            '@item_url' : buzzinfos.doll_url,
            '@member_status' : BFC_Member_Status(object.Owner)
          }
        );
    } else {
      return '';
    }
  }
  
  function printTidbit_block(strings){
    return fillTemplate(tidbitBlockTemplate, strings);
  }  
  

  function printPhotosUser(photos){
    var listImagesHtml = '', msg, extraClass='';
    
    // Add scrollable
    if(photos.Images.length > 6){
      listImagesHtml += '<div class="scrollable-container small-buttons scrollable-container-1">';
      listImagesHtml += '<a class="left browse prev">&lt; &lt;</a>';
      listImagesHtml += '<a class="right browse next">&gt; &gt;</a>';
      listImagesHtml += '<div class="images scrollable">';
      listImagesHtml += '<div class="items">';
      extraClass += "scrollable-page";
    }
    
    $.each(photos.Images, function(index, value){
      listImagesHtml += '<a class="' + extraClass + ' photo" href="' + photos.CollectionUrl + '"><img width="75" height="75" src="' + value + '" /></a>';
    })
    
    // Close Scrollable div
    if(photos.Images.length > 6){
      listImagesHtml += '</div></div></div>';
    }    
    
    if(photos.Images.length>1){
      msg = photos.Images.length + Drupal.t(' new photos were added to <a class="user_name" href="@user_url">@name</a>\'s <a href="@item_url">collection</a>');
    } else {
      msg = Drupal.t('1 new photo was added to <a class="user_name" href="@user_url">@name</a>\'s <a href="@item_url">collection</a>');
    }
    
    msg = fillTemplate(msg, 
        {
          '@name' : photos.Name,
          '@user_url' : photos.Url, 
          '@item_url' : photos.CollectionUrl
        }
    );
                                                  
    return fillTemplate(photoUserTemplate,    
        {
          '@content' : listImagesHtml,
          '@date' : printPostedTime(photos.SortTime),
          '@user_avatar' : printUserAvatar(photos.Owner),
          '@user_url' : photos.Url,
          '@message' : msg
        }
      );
  }
  
  function printWhatsHotFor(objects, what){
    what = what.toLowerCase();
		var html = '<h4>' + Drupal.t('Added the most new !what this week', {'!what': '<span>' + what.toUpperCase() + '</span>'}) + '</h4>', url, restricted = false;

    if(what === 'forums') objects = objects.sort(sortHotterForums);
    else if(what === 'comments') objects = objects.sort(sortHotterComments);
    var topone, width, title, count;
    html += '<dl>';
    
    $.each(objects, function(index, value){
      // Number of post-photos/comments?
      if(value.PostCount != undefined){
        count = value.PostCount;
      } else if(value.Comments.NumberOfComments != undefined) {
        count = value.Comments.NumberOfComments;
      }
      if(topone == undefined){ topone = parseInt(count); }
      width = 100 - Math.round( ( parseInt(count) / topone ) * 100);
      
      if(!User_BFC && typeof(value.Categories) != 'undefined'){
        $.each(value.Categories, function(index2, category){
          if( (typeof(category.Name) != 'undefined') && (category.Name === (site_prefix + 'bfc_exclusive')) ){
            restricted = true;
            return false;
          }
        })
      }
      title = value.Title.replace('| Barbie Collector', '');
      title = limitStr(title, 20);
      
      if( !User_Logged && ((what === 'forums') || restricted) ){
        url = '<a href="/user" onClick="$(\'#header a.loginlink\').click(); return false;" title="'+value.Title+'">' + title + '</a>';
      } else if( !User_BFC && ((what === 'forums') || restricted) ){
        url = '<a href="' + Drupal.settings.mattel_pluck.bfc_card_path + '" title="'+value.Title+'">' + title + '</a>';
      } else {
        url = '<a href="' + value.Url.replace('directforums', 'forums') + '" title="'+value.Title+'">' + title + '</a>';
      }
      html += '<dd class="bar bar' + index  +'"><span class="title">' + url + '<b>' + count + '</b></span><span class="percent" style="width:' + width + '%;"></span></dd>';
    });
    html += '</dl>';

    return html;
  }  
  

  /**********************/
  /*    Add Functions   */
  /**********************/
  function addWhatsHot(object){
    if(object.ObjectType == 'Responses.Custom.CustomCollectionsPageResponse'){
			if ($('#bc_pluck-whats_hot').length) {
				var products = [];
				$.each(mostPhotos, function (i, v) {
					products.push(v.nid);
				});

				$.ajax({
					'url':      '/ajax/bc-pluck/photo',
					'type':     'POST',
					'data': {
						'op':       'top-info',
						'products': products.toString()
					},
					'dataType': 'json',
					'success':  function (data) {
						$.each(mostPhotos, function (i, v) {
							if (typeof(data[v.nid]) != 'undefined') {
					      whatshot['photos'].push({
									'PostCount': v.num,
									'Title':     data[v.nid].title.replace(/<\/?[^>]+(>|$)/g, ""),
									'Url':       data[v.nid].url
								});
							}
						});
		        $('div#whatshotphotos').replaceWith(printWhatsHotFor(whatshot['photos'], 'PHOTOS'));
					}
				});
			}
    } else{
    $.each(object.DiscoveredContent, function(index, value){
      switch(value.ObjectType){
        case 'Models.Forums.ForumDiscussion':
          whatshot['forums'].push(value);
          break;
        case 'Models.External.Article':
          whatshot['comments'].push(value);
          break;
      }
    })
    }
  }

  function addToPrintCollectors(object){
    //Add a SortTime propriety to sort the final array
    if(object.PostedAtTime != undefined){
      object.SortTime = object.PostedAtTime;
    } else if(object.FirstPostDate != undefined) {
      object.SortTime = object.FirstPostDate;
    } else if(object.LastUpdated != undefined){
      object.SortTime = object.LastUpdated;
    }
    recentActivity.push(object);
  }
  
  function addPhotoCollectors(photo){
    var photoItem, imageurl;
    
    if(photosCollection[photo.Owner.DisplayName] == undefined){
      photoItem = {};
      photoItem.Name = photo.Owner.DisplayName;
      photoItem.Owner = photo.Owner;
      photoItem.Url = photo.Owner.PersonaUrl;
      var re = new RegExp('[0-9]+');
      var id = re.exec(photo.Owner.UserKey.Key);
      photoItem.CollectionUrl = "/user/" + id[0] + "/photos";
      photoItem.SortTime = photo.CreatedOn; 
      photoItem.ObjectType = 'Photos';             
      photoItem.Images = [];
      
      photosCollection[photo.Owner.DisplayName] = photoItem;
    } else if(photo.CreatedOn > photosCollection[photo.Owner.DisplayName].SortTime){
      photosCollection[photo.Owner.DisplayName].SortTime = photo.CreatedOn;     
    }
    photosCollection[photo.Owner.DisplayName].Images.push(mattel_pluck.getImageUrl(photo.Image.Full, 'pluck_photo_strip_thumb'));
  }

	function addDoliciousMostPhotos(object) {
		if ($('#bc_shop-dollicious').length && typeof(mostPhotos[1]) != 'undefined') {
			$.ajax({
				'url':      '/ajax/bc-pluck/photo',
				'type':     'POST',
				'data': {
					'op':  'dollicious-info',
					'nid': mostPhotos[1].nid
				},
				'dataType': 'text',
				'success':  function (data) {
					var msg = (mostPhotos[1].num == 1) ? Drupal.t('Tagged in 1 photo') : Drupal.t('Tagged in !num photos', {'!num': mostPhotos[1].num});
					data = data.replace('!num_photos', msg);
					$('.templable', '#bc_shop-dollicious').replaceWith(data);
					Drupal.attachBehaviors( $('.view-dollicious-photos', '#bc_shop-dollicious') );
				}
			});
		}
	}

	function addMostPhotos(object) {
		var prefix = site_prefix + 'product_';
		var values = {};
		$.each(object.Items, function (i, photo) {
			var tags = photo.Tags.split(' ');
			$.each(tags, function (i, tag) {
				if (tag.indexOf(prefix) != -1) {
					var value = tag.substr(prefix.length);

					if (typeof(values[value]) == 'undefined') {
						values[value] = 1;
					}
					else {
						values[value]++;
					}
				}
			});
		});

		$.each(values, function (nid, num) {
			for (var i = 1; i <= 3; i++) {
				if (typeof(mostPhotos[i]) == 'undefined' || mostPhotos[i].num < num) {
					if (i < 3 && typeof(mostPhotos[2]) != 'undefined') {
						mostPhotos[3] = mostPhotos[2];
					}
					if (i < 2 && typeof(mostPhotos[1]) != 'undefined') {
						mostPhotos[2] = mostPhotos[1];
					}

					mostPhotos[i] = {
						'nid': nid,
						'num': num
					};
					break;
				}
			}
		});
	}

  function generatePhotoItems(){
    $.each(photosCollection, function(index, value){
      recentActivity.push(value);
    })
  }
  
  
  /**********************/
  /*   Print Functions  */
  /**********************/  
  function printCollectors(){
    var html = '', isTidbit;
    
    generatePhotoItems();
    recentActivity = recentActivity.sort(sortactivity);

    $.each(recentActivity, function(index, value){   
      isTidbit = false;
      switch(value.ObjectType){
        case 'Models.Reactions.Comment':
          if(value.Categories.length){
            $.each(value.Categories, function(index, category){
              if( (typeof(category.Name) != 'undefined') && (category.Name === (site_prefix + 'tidbits')) ){
                html += printTidbit(value);
                isTidbit = true;
              }
            })
            if(!isTidbit) html += printComment(value);
          } else {
            if( (typeof(value.CommentedOnKey.ObjectType) != 'undefined') && (value.CommentedOnKey.ObjectType == 'Models.Media.PhotoKey') ){
              html += printCommentPhoto(value);
            }else
              html += printComment(value);
          }
          break;
        case 'Models.Forums.ForumDiscussion':
          html += printForumsMsg(value);
          break;
        case 'Photos':
          html += printPhotosUser(value);
          break;
        case 'Models.Custom.CustomItem':
          if( (value.MimeType != undefined) && (value.MimeType === 'FavoriteDoll') ){
            html += printFavDoll(value);
          }
          break;
      }
      
      //Hide the extra items
      if( (index === (HideAfter-1)) && (recentActivity.length > (index+1)) ){
        var showMoreNbr = recentActivity.length - HideAfter;
        html += '<button id="show_more_buzz">' + Drupal.t('Load More (!num)', {'!num':showMoreNbr}) + "</button>";
        html += '<div class="more_buzz hidden">';
      } else if( (index > (HideAfter-1) ) && (index === recentActivity.length) ){
        html += '</div>';
      }
    });
    
    return html;
  }
  
  function printWhatsHot(){
    var html = '';  
    html += printWhatsHotFor(whatshot['comments'], 'COMMENTS');
    html += printWhatsHotFor(whatshot['forums'], 'FORUMS');
    html += '<div id="whatshotphotos"></div>';    
    return html;
  }  

  /**********************/
  /*  Utility Functions */
  /**********************/
  function sortHotterComments(a,b){
    if(a.Comments.NumberOfComments < b.Comments.NumberOfComments){
      return 1;
    } else if(a.Comments.NumberOfComments > b.Comments.NumberOfComments){
      return -1;
    } else {
      return 0;
    }
  }
  
  function sortHotterForums(a,b){
    if(a.PostCount < b.PostCount){
      return 1;
    } else if(a.PostCount > b.PostCount){
      return -1;
    } else {
      return 0;
    }
  }  
  
  function fillTemplate(str, contents){
    $.each(contents, function(index, value) { 
      str = str.replace(new RegExp(index,"g"), value);
    })
    return str;
  }
  
  function BFC_Member_Status(user_object){
    var status = 'barbie';
    if(user_object.ExtendedProfile != undefined){
      $.each(user_object.ExtendedProfile, function(index, value){
        switch(value.Key){
          case 'bfc':
            if(parseInt(value.Value)) status = 'bfc';
            return false;
            break;
        }
      })
    }
    return status;
  }
  
  function printPostedTime(date){
    var diff = datenow - date, result;
    
    if( result = Math.floor( diff / (1000 * 60 * 60 * 24) ) ){
      if(result > 1){
        return result + ' ' + Drupal.t('days ago');
      } else return result + ' ' + Drupal.t('day ago');
    } else if( result = Math.floor( diff / (1000 * 60 * 60) ) ){
      if(result > 1){
        return result + ' ' + Drupal.t('hours ago');
      } else return result + ' ' + Drupal.t('hour ago');
    } else if( result = Math.floor( diff / (1000 * 60) ) ){
      if(result > 1){
        return result + ' ' + Drupal.t('mins ago');
      } else return result + ' ' + Drupal.t('min ago');
    } else {
      return Drupal.t('Less than 1 min ago');
    }
  }
  
  function sortactivity(a,b){    
    if(a.SortTime < b.SortTime){
      return 1;
    } else if(a.SortTime > b.SortTime){
      return -1;
    } else {
      return 0;
    }
  }
    
  function limitStr(str, len){
    var html;
    try{
      if($.browser.msie){
        html = (str.length > len) ? str.substr(0, len).replace(/<\/?[^>]+(>|$)/g, "") + '...' : str;
      } else {
        html = (str.length > len) ? $('<div>' + str.substr(0, len) + '</div>').html() + '...' : str;
      }
    } catch(e){
      html = (str.length > len) ? str.substr(0, len).replace(/<\/?[^>]+(>|$)/g, "") + '...' : str;
    }
    return html;
  }

  
  /***********************/
  /*   Public Functions  */
  /***********************/   
	return {
		'printTidbit_block': printTidbit_block,
		'printWhatsHot' : printWhatsHot,
		'printCollectors' : printCollectors,		
		'addToPrintCollectors' : addToPrintCollectors,
		'addWhatsHot' : addWhatsHot,
    'addPhotoCollectors' : addPhotoCollectors,
		'addMostPhotos' : addMostPhotos,
		'addDoliciousMostPhotos' : addDoliciousMostPhotos,
    'printUserAvatar' : printUserAvatar,
    'limitStr' : limitStr
	};  
  
}

MattelPluckBC = function() {
  var errorlog = [];
  var debug = (Debug && window.console) ? true : false;
  var to_process = false;
  var wheelofjoy = $('<img class="wheelofjoy" title="Loading" alt="Loading" src="/sites/all/themes/barbie_collector/images/icons/icon-wheelOfJoy.gif">');
  var printer = new Printer();
  var site_prefix = Drupal.settings.mattel_pluck.content_prefix;
  var User_BFC = isCurrentUser("BFC");
  var User_Logged = isCurrentUser("LOGGED");
  var photosinbuzz = 15;
  var didPhotoQuery = false;
  var pluck_object = new MattelPluck();

  // Templable
  var actions = new Object();
  var results = new Object();
  
  
  /******************************/
  /*  Get information functions */
  /******************************/    
  function getComments(articleId) { 
    if(debug) console.log('get comments ' + articleId);
    var commentsPageRequest = new PluckSDK.CommentsPageRequest();
    commentsPageRequest.ItemsPerPage = 4;
    commentsPageRequest.CommentedOnKey = new PluckSDK.ExternalResourceKey();
    commentsPageRequest.CommentedOnKey.Key = articleId;
    commentsPageRequest.OneBasedOnPage = 1;
    pluck_object.queue(commentsPageRequest);
    
    to_process = true;
  }

  function getCommentsPhoto(photoId) { 
    if(debug) console.log('get comments ' + photoId);
    var commentsPageRequest = new PluckSDK.CommentsPageRequest();
    commentsPageRequest.ItemsPerPage = 4;
    commentsPageRequest.CommentedOnKey = new PluckSDK.PhotoKey();
    commentsPageRequest.CommentedOnKey.Key = photoId;
    commentsPageRequest.OneBasedOnPage = 1;
    pluck_object.queue(commentsPageRequest);
    
    to_process = true;
  }

  function getNumberComments(articleId) {
    if(debug) console.log('getnumbercomments' + articleId);
    
    var articleRequest = new PluckSDK.ArticleRequest();
    articleRequest.ArticleKey = new PluckSDK.ExternalResourceKey();
    articleRequest.ArticleKey.Key = articleId;
    pluck_object.queue(articleRequest);
    
    to_process = true;
  }
  
  function getUser(userId){
    if (debug) console.log('Get User');
    myRequest = new PluckSDK.UserRequest();
    if(userId != 'current') myRequest.UserKey = new PluckSDK.UserKey( {Key:userId} ); 
    pluck_object.queue(myRequest);
    
    to_process = true;    
  } 
  
  function getActivity(){
    if (debug) console.log('Get activity');
    
    //Articles/Tidbits
    var activityRequest = new PluckSDK.DiscoverContentActionRequest();
  	activityRequest.Activity = PluckSDK.DiscoveryActivity.Recent;
  	activityRequest.Age = 10;
    activityRequest.MaximumNumberOfDiscoveries = 10;  	
  	activityRequest.Type = PluckSDK.ContentType.Article;
  	activityRequest.LimitToContributors = [ PluckSDK.UserTier.All, PluckSDK.UserTier.Trusted ];
  	activityRequest.Sections = [];  	
  	activityRequest.Sections.push( new PluckSDK.DiscoverySection( {Name: site_prefix + 'site'} ) );
  	activityRequest.Categories = []; 
  	activityRequest.Categories.push( new PluckSDK.DiscoveryCategory( {Name: site_prefix + 'comments'} ) );    	    	
    pluck_object.queue(activityRequest);
    
    //UserPhotoGallery
    didPhotoQuery = true;
    var customCollectionsPageRequest = new PluckSDK.CustomCollectionsPageRequest();
    customCollectionsPageRequest.CustomCollectionKey = new PluckSDK.CustomCollectionKey();
    customCollectionsPageRequest.CustomCollectionKey.Key = site_prefix + 'photo';
    customCollectionsPageRequest.ItemsPerPage = 40;
    customCollectionsPageRequest.OneBasedOnPage = 1;
    customCollectionsPageRequest.Sort = new PluckSDK.TimestampSort();
    customCollectionsPageRequest.SortOrder = PluckSDK.SortEnum.TimeStampDescending;
    pluck_object.queue(customCollectionsPageRequest);
    
    //Favorite Doll
    var favoriteDollsPageRequest = new PluckSDK.CustomCollectionsPageRequest();
    favoriteDollsPageRequest.CustomCollectionKey = new PluckSDK.CustomCollectionKey();
    favoriteDollsPageRequest.CustomCollectionKey.Key = site_prefix + 'fav_dolls';
    favoriteDollsPageRequest.ItemsPerPage = 10;
    favoriteDollsPageRequest.OneBasedOnPage = 1;
    favoriteDollsPageRequest.Sort = new PluckSDK.TimestampSort();
    favoriteDollsPageRequest.SortOrder = PluckSDK.SortEnum.TimeStampDescending;
    pluck_object.queue(favoriteDollsPageRequest);
    
    // Post Forum
    var postForumsRequest = new PluckSDK.DiscoverContentActionRequest();
  	postForumsRequest.Activity = PluckSDK.DiscoveryActivity.Recent;
  	postForumsRequest.Age = 15;
  	postForumsRequest.Type = PluckSDK.ContentType.Discussion;
  	postForumsRequest.LimitToContributors = [ PluckSDK.UserTier.All, PluckSDK.UserTier.Trusted ];
  	postForumsRequest.Sections = [];
  	postForumsRequest.Sections.push( new PluckSDK.DiscoverySection( {Name:"all"} ) );  	
  	postForumsRequest.Categories = [];
  	postForumsRequest.MaximumNumberOfDiscoveries = 10;
    pluck_object.queue(postForumsRequest);      
    
    to_process = true;
  }
  
  function getMostActiveNews(){
    if (debug) console.log('Get Active news');  
    var activeNewsRequest = new PluckSDK.DiscoverContentActionRequest();
  	activeNewsRequest.Activity = PluckSDK.DiscoveryActivity.Commented;
  	activeNewsRequest.Age = 7;
  	activeNewsRequest.Type = PluckSDK.ContentType.Article;
  	activeNewsRequest.LimitToContributors = [ PluckSDK.UserTier.All, PluckSDK.UserTier.Trusted ];
  	activeNewsRequest.Sections = [];
  	activeNewsRequest.Sections.push( new PluckSDK.DiscoverySection( {Name: site_prefix + 'site'} ) );  	  	
  	activeNewsRequest.Categories = [];
  	activeNewsRequest.Categories.push( new PluckSDK.DiscoveryCategory( {Name: site_prefix + 'comments'} ) );   	
  	activeNewsRequest.MaximumNumberOfDiscoveries = 3;
    pluck_object.queue(activeNewsRequest);      
    
    to_process = true;
  }
  
  function getMostActiveDiscussionss(){
    if (debug) console.log('Get Active news');  
    var activityRequest = new PluckSDK.DiscoverContentActionRequest();
  	activityRequest.Activity = PluckSDK.DiscoveryActivity.Commented;
  	activityRequest.Age = 7;
  	activityRequest.Type = PluckSDK.ContentType.Discussion;
  	activityRequest.LimitToContributors = [ PluckSDK.UserTier.All, PluckSDK.UserTier.Trusted ];
  	activityRequest.Sections = [];
  	activityRequest.Sections.push( new PluckSDK.DiscoverySection( {Name:"all"} ) );  	
  	activityRequest.Categories = [];
  	activityRequest.MaximumNumberOfDiscoveries = 3;
    pluck_object.queue(activityRequest);      
    
    to_process = true;
  }  

  function getGallery(GalleryKey){
    var galleryRequest = new PluckSDK.GalleryRequest();
    galleryRequest.GalleryKey = new PluckSDK.GalleryKey();
    galleryRequest.GalleryKey.Key = GalleryKey;
    
    pluck_object.queue(galleryRequest);        
    
    to_process = true;
  }
  
  function getPhotoGallery(GalleryKey){
    var photosGalleryRequest = new PluckSDK.PhotosPageRequest();
    photosGalleryRequest.GalleryKey = new PluckSDK.GalleryKey();
    photosGalleryRequest.GalleryKey.Key = GalleryKey;
    photosGalleryRequest.ItemsPerPage = 3;

    pluck_object.queue(photosGalleryRequest);        
    
    to_process = true;
  }
  
  
  function getInboxNbrNewMsg(){
    if(debug) console.log('Get Inbox Nbr Msg');
    var PrivateMessagesRequest = new PluckSDK.PrivateMessageFolderListRequest();
    pluck_object.queue(PrivateMessagesRequest);
    
    to_process = true;
  };
  
	function getDollicious() {
		if (didPhotoQuery == false) {
		  var customCollectionsPageRequest = new PluckSDK.CustomCollectionsPageRequest();
		  customCollectionsPageRequest.CustomCollectionKey = new PluckSDK.CustomCollectionKey();
		  customCollectionsPageRequest.CustomCollectionKey.Key = site_prefix + 'photo';
		  customCollectionsPageRequest.ItemsPerPage = 40;
		  customCollectionsPageRequest.OneBasedOnPage = 1;
		  customCollectionsPageRequest.Sort = new PluckSDK.TimestampSort();
		  customCollectionsPageRequest.SortOrder = PluckSDK.SortEnum.TimeStampDescending;
		  pluck_object.queue(customCollectionsPageRequest);

	    to_process = true;
		}
		didPhotoQuery = true;
	}
  
  /*******************************/
  /*  Save information functions */
  /*******************************/     
  function makeTidbit(articleId, commentText){ 
    if (debug) console.log('creating comment');
    var article = new PluckSDK.UpdateArticleActionRequest();
    article.ArticleKey = new PluckSDK.ExternalResourceKey( {Key:articleId} );
    article.Section = new PluckSDK.DiscoverySection( {Name : site_prefix + 'site'} );
    article.Categories = [];
    article.Categories.push( new PluckSDK.DiscoveryCategory({Name : site_prefix + 'tidbits'}) );
    article.Categories.push( new PluckSDK.DiscoveryCategory({Name : site_prefix + 'comments'}) );    
    article.OnPageUrl = location.href; 
    article.OnPageTitle = document.title.replace('| Barbie Collector', '');
    article.ReviewItemState = PluckSDK.ReviewItemState.Active;
    pluck_object.queue(article);    
    
    var action = new PluckSDK.CommentActionRequest(); 
    action.CommentedOnKey = new PluckSDK.ExternalResourceKey( {Key:articleId} );
    action.Section = new PluckSDK.DiscoverySection( {Name : site_prefix + 'site'} );
    action.Categories = [];
    action.Categories.push( new PluckSDK.DiscoveryCategory({Name : site_prefix + 'tidbits'}) );
    action.Categories.push( new PluckSDK.DiscoveryCategory({Name : site_prefix + 'comments'}) );     
    action.OnPageUrl = location.href; 
    action.OnPageTitle = document.title.replace('| Barbie Collector', ''); 
    action.Body = commentText;
    pluck_object.queue(action);
    to_process = true;
    
    process(); 
  }
  
  function thumpComment(commentKey, parentKey, score){
    if (debug) console.log('Thumpup');
    var thumpRequest = new PluckSDK.SetItemScoreActionRequest();
    thumpRequest.TargetKey = new PluckSDK.CommentKey( {Key:commentKey} );
    thumpRequest.Score = score;
    thumpRequest.ScoreId = "Thumbs";
    thumpRequest.ParentKey = new PluckSDK.ExternalResourceKey( {Key:parentKey} );

    pluck_object.queue(thumpRequest);
    to_process = true;    
    process();
  }
  
  function reportAbuse(id, reason, description){
    if (debug) console.log('Report Abuse');
    var abuseAction = new PluckSDK.ReportAbuseActionRequest();
  	abuseAction.AbuseOnKey = id;
  	abuseAction.Reason = reason;
  	abuseAction.Description = description;
    pluck_object.queue(abuseAction);
    to_process = true;    
    process();
  }
  
  /************************/
  /*  Templable Functions */
  /************************/  
  /* Find all the informations needed and send the request */
  this.processTemplate = function(context) {
    if(debug) console.log('process template');
    var regex, templates, matches, matchIdx, theMatch, varName, varFunction, varArg, tocall={};

    regex = /\@data\.[^\@]+\@/g;
    matches = [];
    
    templates = $('.templable:not(.inprogress)', context);
    
    $.each(templates, function(index, value) {
      $(value).addClass('inprogress');
      matches = value.innerHTML.match(regex);
      if (matches != null) {
        for (matchIdx = 0; matchIdx < matches.length; matchIdx++) {
          theMatch = matches[matchIdx];
          varName = theMatch.substring(6, theMatch.length - 1);
          varName = varName.split('-');
          varFunction = varName[0];
          varArg =  varName[1];
          if (typeof actions[varFunction] != "undefined") {
            if(tocall[varFunction] == undefined)
              tocall[varFunction] = actions[varFunction];
            if(tocall[varFunction].Args == undefined)
              tocall[varFunction].Args = [];
            tocall[varFunction].Args.push(varArg);
          }
        }
      }
    })
    
    $.each(tocall, function(index, funct){
      DeDupArray(funct.Args); //Avoid to call two times the same function with same args
      $.each(funct.Args, function(index, arg){
        funct.func(arg);
      })
    })

    process();
  }  
  
  
  /* Replace all the informations needed by their value */
  function post_processTemplate(dataObj, template) {
    if(debug) console.log('post process');
    
    var regex, elements, template, matches, matchIdx, theMatch, varName, varFunction, varArg, varExtraArgs = null,  htmlresult;
    regex = /\@data\.[^\@]+\@/g;
    
    elements = $('.templable');
    
    $.each(elements, function(index, value) { 
      matches = value.innerHTML.match(regex);
      if (matches != null) {
        for (matchIdx = 0; matchIdx < matches.length; matchIdx++) {
          theMatch = matches[matchIdx];
          varName = theMatch.substring(6, theMatch.length - 1);
          varName = varName.split('-');
          varFunction = varName[0];
          varArg =  varName[1];
          if(varName[2]) varExtraArgs = varName[2];
          if (typeof results[varArg] != "undefined") {     
            $(value).html( actions[varFunction].result(results[varArg], varExtraArgs) ).removeClass('templable').removeClass('inprogress');
            Drupal.attachBehaviors( $(value) );              
          }
        }
      }
    });
    
    //Reinitialise the Results object;
    results = new Object();
    //Fire event
    $('.waiting').trigger('end_post_process');
  }
  
  /**********************/
  /* Callback Function  */
  /**********************/    
  function masterCallback(responses) {
    if (debug && window.console && window.console.dir) window.console.dir(responses); 

    $.each(responses, function(index, response) { 
      if (response.ResponseStatus.StatusCode != PluckSDK.ResponseStatusCode.OK) { 
          if ( itemNotFound(response) ) { 
              errorlog.push("This article does not exist in the Pluck database"); 
          } else { 
              errorlog.push("Unhandled Pluck exception"); 
          } 
      } else {      
        switch (response.ObjectType){
          case 'Responses.Discovery.DiscoverContentResponse':
            switch (response.Activity){
              //Whatshot
              case 'Commented':
                results['whatshot'] = ''; // No null
                printer.addWhatsHot(response);
                break;
              //Activity Feed
              case 'Recent':
                $.each(response.DiscoveredContent, function(index, content) { 
                  switch(content.ObjectType){
                    case 'Models.External.Article':
                      if(content.Comments.NumberOfComments > 0){
                        var allowed_article = true;
                        if(!User_BFC){
                          $.each(content.Categories, function(index, value){
                            if(value.Name == site_prefix + "bfc_exclusive"){
                              allowed_article = false;
                              return false;
                            }
                          });
                        }
                        if(allowed_article) getComments(content.ArticleKey.Key);
                      }
                      break;
                    case 'Models.Media.Gallery':
                      getPhotoGallery(content.GalleryKey.Key);
                      break;
                    case 'Models.Forums.ForumDiscussion':
                      printer.addToPrintCollectors(content);
                      break;                      
                  } 
                })
                break; 
            }
            break;
          case 'Responses.Reactions.CommentsPageResponse':
            results[response.CommentedOnKey.Key] = response.Items;
            $.each(response.Items, function(index, item) {
              switch(item.ObjectType){
                case 'Models.Reactions.Comment':
                  //if( (typeof(item.Section) != 'undefined') && (typeof(item.Section.Name) != 'undefined') && (item.Section.Name === (site_prefix + 'site')) )
                  printer.addToPrintCollectors(item);
                  break;
              }
            })
            break;
          case 'Responses.External.ArticleResponse':
            var myArticle = response.Article;
            results[myArticle.ArticleKey.Key] = myArticle
            break;     
          case 'Responses.System.ActionResponse':       
            $.each(response.KeyActions, function(index, action) {
              switch(action.ActionType){
                case PluckSDK.KeyActionType.Created:
                  if(action.Key.ObjectType === 'Models.Reactions.CommentKey') // For exemple after a tidbit has been added
                    window.location.search = window.location.search + "?showall=yes";
                  break;
              }
            })
            break;    
          case 'Responses.Reactions.ItemScoresResponse':      
            $.each(response.ItemScores, function(index, score) {
              switch(score.ObjectType){
                case 'Models.Reactions.ItemScore':
                  results[score.ParentKey.Key] = score;
                  break;
              }
            })
            break;
          
          case 'Responses.Custom.CustomCollectionsPageResponse':
          	if (typeof(response.Items[0]) != 'undefined' && response.Items[0].ObjectType == 'Models.Media.Photo') {
          		printer.addMostPhotos(response);
	            printer.addWhatsHot(response);
	            printer.addDoliciousMostPhotos(response);
          	}
            
            var i=0;
            $.each(response.Items, function(index, item){
              switch(item.ObjectType){
                case 'Models.Media.Photo':
                  if(index < photosinbuzz ) printer.addPhotoCollectors(item);
                  if( (item.NumberOfComments != 0) && (i<5) ){
                    getCommentsPhoto(item.PhotoKey.Key);
                    i++;
                  }
                  break;
                case 'Models.Custom.CustomItem':
                  if( (item.MimeType != undefined) && (item.MimeType === "FavoriteDoll") ){  
                    printer.addToPrintCollectors(item);
                  }
                  break;
              }
            })
            break;
            
          case 'Responses.PrivateMessaging.PrivateMessageFolderListResponse':
            $.each(response.FolderList, function(index, folder){
              switch(folder.FolderID){
                case 'Inbox':
                results['inbox'] = folder.UnreadMessageCount;
                break;
              
              }
            })
            break;
            
          case 'Responses.Users.UserResponse':
            results[response.User.UserKey.Key] = response.User;
            
        }
      }
    })
    
    // Some request don't need the information of the response so we just raise a event to tell them it's done 
    $('.waiting').trigger("loaded"); 
      
    // We have all the informations we need, we print the results
    if(!to_process) results['activityfeed'] = printer.printCollectors();
    
    // If information to replace in the template
    if( !isEmpty(results) ) post_processTemplate();
    
    process();
  }
  
  
  /*********************/
  /* Process functions */
  /*********************/  
  function process(){
    if(to_process){
      if(debug) console.log('process');    
      pluck_object.setResultsCallback(masterCallback);    
      pluck_object.send();
      to_process = false;
    }
  }
  
  /*********************/
  /*  Errors Functions */
  /*********************/   
  this.geterrors = function(){
    console.log(errorlog);
  }
  
  function itemNotFound(sdkResponse) { 
    var exceptionCode; 
    for (var exIdx = 0; exIdx < sdkResponse.ResponseStatus.Exceptions.length; exIdx++) { 
        exceptionCode = sdkResponse.ResponseStatus.Exceptions[exIdx].ExceptionCode; 
        if (exceptionCode === PluckSDK.ResponseExceptionCode.ObjectNotFoundInStorage) { 
            return true; 
        } 
    } 
    return false; 
  }     
    
  /**********************/
  /* Actions availiable */
  /**********************/
  actions['getNbrComments'] = {
    'func' : getNumberComments,
    'result' : function(object) { return object.Comments.NumberOfComments}
  };
  actions['getComments'] = {
    'func' : getComments,
    'result' : function(object) { return object.Comments}
  };
  actions['getTidbits'] = {
    'func' : function(articleId) { return getComments(articleId); },
    'result' : function(object) {
      if(object.length === 0){
        return '<span class="tidbit-empty">' + Drupal.t('Be the first to add a comment!') + '</span>';
      }
      var html = '', score, showall;
      object.sort(sortTidbits);
      showall = ( (window.location.href.toLowerCase().indexOf('showall=yes') != -1) || (window.location.href.toLowerCase().indexOf('plckfindcommentkey') != -1) );
      $.each(object, function(index, tidbit) {
        score = tidbit.Score;
        score = (score>0) ? ('+' + score) : 0;
        
        html += printer.printTidbit_block(
          {
            '@name' : tidbit.Owner.DisplayName,
            '@body' : tidbit.Body,
            '@CommentKey' : tidbit.CommentKey.Key,
            '@MinCommentKey' : tidbit.CommentKey.Key.replace('CommentKey:', ''),
            '@user_url' : tidbit.Owner.PersonaUrl,
            '@score' : score,
            '@articleId' : tidbit.Parent.ArticleKey.Key        
          }     
        );
        if( (!showall) && (object.length > 1) && (index===0) ){
          html += '<div id="show_more_tidbits" class="more-btn"><span>' + Drupal.t('Load More') + ' (' + (object.length - 1) + ')</span>';
          html += '<img src="/sites/all/themes/barbie_collector/images/icons/icon-dropdown-down.png">';
          html += '</div>';
          html += '<div class="more_tidbit hidden">';
        }
        if( (!showall) && (object.length > 1) && (index===object.length) ) html += '</div>';
      })
      return html;
    }
  };
  actions['getResultThumb'] = {
    'func' : null,
    'result' : function(object) { return '+' + object.ScoreCount }
  };
  
  actions['getWhatshot'] = {
    'func' : function(){
      getMostActiveNews();
      getMostActiveDiscussionss();
    },
    'result' : function(html) { return printer.printWhatsHot(); }
  };
  
  actions['getActivityFeed'] = {
    'func' : getActivity,
    'result' : function(html) { return html; }
  }; 
  
  actions['getInboxNbrNewMsg'] = {
    'func' : getInboxNbrNewMsg,
    'result' : function(data, extraArgs) {
      var numberMsg = parseInt(data), html = '';
      if(extraArgs == "forums"){
        html = '<span';
        if(numberMsg > 0) html += ' class="new_msg"';
        html += '><a href="/user_inbox/">' + Drupal.t('Inbox (!num)', {'!num':numberMsg}) + '</a>';
      } else {
        if(numberMsg===1){
          html = '<span class="new_msg"><a href="/user_inbox/">' + Drupal.t('You have a new private message!') + '</a>';
        } else if(numberMsg>1) {
          var text = Drupal.t('You have !nbr new private messages!', {'!nbr' : numberMsg});
          html = '<span class="new_msg"><a href="/user_inbox/">' + text + '</a></div>';
        }
      }
      

      return html;
    }
  };   
  
  actions['getUser'] = {
    'func' : getUser,
    'result' : function(object, extraArgs) {
      var html = '';
      switch (extraArgs){
        case 'Avatar':       
          html += '<a href="' + object.PersonaUrl + '"><img src="'+ object.AvatarPhotoUrl + '"/></a>';
          break;
        case 'Bio':
          if(object.AboutMe != undefined) html += printer.limitStr(object.AboutMe, 155);
          break;
      }
      return html;
    }
  };

	actions['getDollicious'] = {
		'func' : getDollicious,
		'result' : function(html) { return html; }
	}

  /**********************/
  /*      Triggers       */
  /**********************/
  this.user_overlay = function(context){
    $('.persona_overlay', context).each(function(index, value){
      var overlay, lien;
      overlay = $('.user_overlay', $(this) );
      lien = $('.avatar_img', $(this) );
      lien.mouseenter(function(){
        overlay.fadeIn('normal');
      })
      overlay.mouseleave(function(){
        $(this).fadeOut('normal', function(){
          $(this).hide();
        })
      })      
    })
  }
  
  this.abuse_flag = function(context){
    $('a.abuselink', context).each(function(index, value){
      var id;
      $(this).click(function(){
        var abuse_key = $(this).attr('rel');
        if( abuse_key[0] == '#' ){
          abuse_key = abuse_key.substr(1);
        }
        if( $(this).hasClass('comment') ){
          id =  new PluckSDK.CommentKey( {Key: abuse_key } );
        } else if( $(this).hasClass('photo') ) {
          id =  new PluckSDK.PhotoKey( {Key: abuse_key } );
        } else {
          id =  new PluckSDK.CustomItemKey( {Key: abuse_key } );
        }
        createReportAbuse(id);
        return false;
      })
    });
  }

  $('button#show_more_buzz').live('click', function(){
    $(this).remove();
    $('div.more_buzz').hide().removeClass('hidden').slideDown('normal');
  })
  
  $('#show_more_tidbits').live('click', function(){
    $(this).remove();
    $('div.more_tidbit').hide().removeClass('hidden').slideDown('normal');
  })  
  
  $('a.add_tidbit').click(function(){
    if(!User_Logged){
      if(!$(this).hasClass('done')) $(this).parent().append( Drupal.t('<div id="login-required">Only registered users can add tidbits.<br/>Please <a href="/user" onClick="$(\'#header a.loginlink\').click(); return false;">login</a>.</div>') );
      $(this).addClass('done');      
      return false;
    }
    
    var num_doll = $(this).parent().attr('class');
    
    var content_overlay = $('<div id="tidbit_overlay">' +
    '<a id="close-bouton" class="close"></a>' +
    '<div class="contentWrap">' +
      '<form id="tidbit_form">' +
      '<h3 class="overlay-title">Add Comment</h3>' +
      '<fieldset>' +
        '<div class="form-item" id="edit-body-wrapper">' +
          '<textarea cols="60" rows="5" name="body" id="edit-body" class="form-textarea resizable required"></textarea>' +
        '</div>' +
      '</fieldset>' +
      '<input name="op" id="edit-submit" value="Save" class="form-submit" type="submit">' +
      '</form>' +
    '</div>' +
    '</div>');
    
    var action = function(){
      if( $(this).find("#edit-body").val() ) {
        makeTidbit(num_doll, $(this).find("#edit-body").val() );
        $(this).append(wheelofjoy);
      }
      return false;
    }
    
    createOverlay(content_overlay, 'form#tidbit_form', action);
    		
    return false;
  })
  
  $('div.tidbit_rating a').live('click', function(){
    if(!$(this).hasClass('done')){
      var commentKey = $(this).attr('href').slice(1);
      thumpComment(commentKey, $(this).attr('rel'), "1");
      var newscore = parseInt( $(this).html() ) + 1;
      $(this).html('<span class="templable"><span>@data.getResultThumb-' + $(this).attr('rel') + '@</span>' + $(this).html() + '</span>');
      $(this).addClass('done');
    } else {
      if(!$(this).parent().hasClass('already_scored')){
        var already_scored = $('<div class"error">' + Drupal.t('You already voted for this comment.') + '</div>');
        $(this).parent().append( already_scored ).addClass('already_scored');
        window.setTimeout(function(){
          already_scored.fadeOut('slow', function(){
            $(this).parent().removeClass('already_scored');
            $(this).remove();
          })
        }, 1000);
      }
    }
    return false;
  })  
  
  //To do : Change the way it works
  $('.waiting').live('end_post_process', function(){
    //If a user comes from the landing page, we highlight the tidbit
    var tidbit = window.location.href.indexOf('plckFindCommentKey');
    if(tidbit){
      tidbit = window.location.href.substring(tidbit + "plckFindCommentKey=CommentKey:".length, window.location.href.length);
      var end = (tidbit.indexOf('&') != -1) ? tidbit.indexOf('&') : tidbit.length;
      tidbit = tidbit.substring(0,end);
      if($(this).attr('id') === tidbit) $(this).addClass('highlight');
    }  
  })
  
  
  /**********************/
  /*      Vracs        */
  /**********************/
  function DeDupArray(a){
    a.sort();
    for (var i = 1; i < a.length; i++){
      if (a[i-1] === a[i])
        a.splice(i, 1);
    }
  }
    
  function createReportAbuse(id){
    var report_abuse_overlay = $('<div id="tidbit_overlay">' +
    '<a id="close-bouton" class="close"></a>' +
    '<div class="contentWrap">' +
      '<form id="tidbit_abuse_form">' +
      '<h3 class="overlay-title">Report Abuse</h3>' +
      '<fieldset>' +
        '<div class="form-item" id="edit-title-wrapper">' +
          '<select size="1" id="edit-reason" class="required" name="reason">' +
             '<option>Obscenity/Vulgarity</option>'+
             '<option>Hate Speech</option>'+
             '<option>Personal Attack</option>'+
             '<option>Advertising/Spam</option>'+
             '<option>Copyright/Plagiarism</option>'+
             '<option>Other</option>'+
          '</select>' +
        '</div>' +      
        '<div class="form-item" id="edit-body-wrapper">' +
          '<label for="edit-body">Comment (optional):</label><textarea cols="60" rows="5" name="body" id="edit-body" class="form-textarea"></textarea>' +
        '</div>' +
      '</fieldset>' +
      '<input name="op" id="edit-submit" value="Save" class="form-submit" type="submit">' +
      '</form>' +
    '</div>' +
    '</div>');
    
    var action = function(){
      reportAbuse(id, $(this).find("#edit-reason").val(), $(this).find("#edit-body").val());
      $(this).append(wheelofjoy);
      $(this).bind('loaded',function(){
        $(this).html(Drupal.t('Thank you! Your report has been taken in account.'));
      }).addClass('waiting');
      return false;
    }
    
    createOverlay(report_abuse_overlay, 'form#tidbit_abuse_form', action);
  
  }
  
  function isEmpty(obj) {
    for(var prop in obj) {
      if(obj.hasOwnProperty(prop))
        return false;
    }
    return true;
  }  
  
  function sortTidbits(a,b){
    if(a.Score < b.Score){
      return 1;
    } else if(a.Score > b.Score){
      return -1;
    } else {
      return 0;
    }
  }
    
  function createOverlay(content, trigger, action){
    var wrapoverlay = content.appendTo( $('body') );
    wrapoverlay.find(trigger).submit(action);
    wrapoverlay.overlay({
        fixed:false,
        load:true,
        mask: {
        	color: '#000',
        	loadSpeed: 0,
        	closeSpeed: 0,
        	startOpacity: 0.4,
        	opacity: 0.6
        }, 
        onClose : function() {
        	wrapoverlay.remove();
        }
  		});
  }
}
 
/*************
*  Instantiate
*************/
Drupal.behaviors.bc_pluck_abuse_flag = function(context) {
  if (typeof(PluckSDK) != 'undefined') {
    if (typeof(mattel_pluck_bc) == 'undefined') {
      mattel_pluck_bc = new MattelPluckBC();
    }
    mattel_pluck_bc.abuse_flag(context);
	}
};

Drupal.behaviors.bc_pluck_user_overlay = function(context) {
  if (typeof(PluckSDK) != 'undefined') {
    if (typeof(mattel_pluck_bc) == 'undefined') {
      mattel_pluck_bc = new MattelPluckBC();
    }
    mattel_pluck_bc.user_overlay(context);
	}
};


Drupal.behaviors.bc_pluck_templable = function(context) {
  if (typeof(PluckSDK) != 'undefined') {
    if (typeof(mattel_pluck_bc) == 'undefined') {
      mattel_pluck_bc = new MattelPluckBC();
    }
	  mattel_pluck_bc.processTemplate(context);
  }
};
;
var PluckPhotoInfo = function () {
	var pluckAccountId = Drupal.settings.mattel_pluck.profile_user_identifier;
	var pluckUserPrefix = Drupal.settings.mattel_pluck.user_prefix;
	var pluckContentPrefix = Drupal.settings.mattel_pluck.content_prefix;
	var baseUrl = Drupal.settings.mattel_pluck.base_url;

	var gotPhotoInfo = false;
	var totalPhotos;

	var productPhotos = {};

	function bind(context) {
		if (gotPhotoInfo) {
			$('#tabs span.tab', context).each(function () {
				if ( typeof(pluckAccountId) != 'undefined' && $.trim($(this).text()) == Drupal.t('Photos') ) {
					var text = $.trim( $(this).text() + ' (' + totalPhotos + ')');
					$(this).text(text);
				}
			});

			if ($('.collection-list-photos', context).length) {
				var customCollectionsPageRequest = new PluckSDK.CustomCollectionsPageRequest();
				customCollectionsPageRequest.CustomCollectionKey = new PluckSDK.CustomCollectionKey();
				customCollectionsPageRequest.CustomCollectionKey.Key = pluckContentPrefix + 'user_' + pluckAccountId;
				customCollectionsPageRequest.ItemsPerPage = totalPhotos;
				customCollectionsPageRequest.OneBasedOnPage = 1;
				customCollectionsPageRequest.Sort = new PluckSDK.TimestampSort();
				customCollectionsPageRequest.Sort.SortOrder = PluckSDK.SortEnum.TimeStampDescending;

				mattel_pluck.queue(customCollectionsPageRequest);
				mattel_pluck.setResultsCallback(setCollectionListPhotos);
				mattel_pluck.send();
			}
		}
		else {
			setTimeout(function () {bind(context)}, 1000);
		}
	}

	function setPhotoInfo(responses) {
		if (responses[0].ResponseStatus.StatusCode == PluckSDK.ResponseStatusCode.OK) {
			totalPhotos = responses[0].TotalItems;
			gotPhotoInfo = true;
		}
	}

	function setCollectionListPhotos(responses) {
		if (responses[0].ResponseStatus.StatusCode == PluckSDK.ResponseStatusCode.OK) {
			var prefix = pluckContentPrefix + 'product_';

			$.each(responses[0].Items, function (foo, photo) {
				var tags = photo.Tags.split(' ');

				$.each(tags, function (bar, tag) {
					if (tag.indexOf(prefix) != -1) {
						var nid = tag.substr(prefix.length);

						if (typeof(productPhotos[nid]) == 'undefined') productPhotos[nid] = [];
						productPhotos[nid].push(photo);
					}
				});
			});

			$('.collection-list-photos').each(function () {
				populateCollectionListPhotos(this, 0);
			});
		}
	}

	function populateCollectionListPhotos(elem, page) {
		var nid = elem.id.split('-')[2];

		if (typeof(productPhotos[nid]) != 'undefined' && productPhotos[nid].length) {
			var uploadForm = $('.upload-photo', elem)[0];
			var html = '' +
'<span class="pluck-photo-page-info">' +
	'<span class="pluck-photo-page-info-total"></span>' +
	'<span id="upload-form"></span>' +
'</span>' +
'<div class="pluck-photos">' +
	'<span class="pluck-photo-pager-prev" style="display: none;">' + Drupal.t('Previous') + '</span>' +
	'<ul class="pluck-photo-selection-gallery"></ul>' +
	'<span class="pluck-photo-pager-next" style="display: none;">' + Drupal.t('Next') + '</span>' +
'</div>';

			$(elem).html(html).find('#upload-form').replaceWith(uploadForm);
			if (typeof(pluck_photo_upload) != 'undefined') {
				pluck_photo_upload.bind(elem);
			}
			$('.pluck-photo-page-info-total', elem).text((productPhotos[nid].length == 1) ? Drupal.t('1 photo') : Drupal.t('!num photos', {'!num': productPhotos[nid].length}));

			for (var foo = page * 3; foo < (page + 1) * 3 && foo < productPhotos[nid].length; foo++) {
				$('.pluck-photo-selection-gallery', elem).append('<li class="pluck-photo-gallery-item" id="' + productPhotos[nid][foo].PhotoKey.Key + '"><img src="' + mattel_pluck.getImageUrl(productPhotos[nid][foo].Image.Full, 'pluck_photo_strip_thumb') + '" /></li>');
			}

			$('.pluck-photo-gallery-item', elem).click(function () {
				var key = this.id;
				window.location.assign(baseUrl + '/user/' + pluckAccountId.substr(pluckUserPrefix.length) + '/photos/' + key + '#user-photo');
			});
			if (page > 0) {
				$('.pluck-photo-pager-prev', elem).show().click(function () {
					populateCollectionListPhotos(elem, (page - 1));
				});
			}
			if ((page + 1) * 3 < productPhotos[nid].length) {
				$('.pluck-photo-pager-next', elem).show().click(function () {
					populateCollectionListPhotos(elem, (page + 1));
				});
			}
		}
	}

	function getTotalPhotos(elems) {
		var process = false;

		elems.each(function () {
			var customKey = $(this).attr('rel');
			process = true;

			var customCollectionsPageRequest = new PluckSDK.CustomCollectionsPageRequest();
			customCollectionsPageRequest.CustomCollectionKey = new PluckSDK.CustomCollectionKey();
			customCollectionsPageRequest.CustomCollectionKey.Key = customKey;
			customCollectionsPageRequest.OneBasedOnPage = 0;

			mattel_pluck.queue(customCollectionsPageRequest);
		});

		if (process) {
			mattel_pluck.setResultsCallback(setTotalPhotos);
			mattel_pluck.send();
		}
	}

	function setTotalPhotos(responses) {
		$.each(responses, function (i, response) {
			if (response.ResponseStatus.StatusCode == PluckSDK.ResponseStatusCode.OK) {
				var total = response.TotalItems;
				var msg = (total == 1) ? Drupal.t('1 photo') : Drupal.t('!num photos', {'!num': total});
				var rel = response.CustomCollectionKey.Key;

				$('.photo-info-total-photos[rel="' + rel + '"]').text(msg);
			}
		});
	}

	if (typeof(pluckAccountId) != 'undefined') {
		var customCollectionsPageRequest = new PluckSDK.CustomCollectionsPageRequest();
		customCollectionsPageRequest.CustomCollectionKey = new PluckSDK.CustomCollectionKey();
		customCollectionsPageRequest.CustomCollectionKey.Key = pluckContentPrefix + 'user_' + pluckAccountId;
		customCollectionsPageRequest.OneBasedOnPage = 0;

		mattel_pluck.queue(customCollectionsPageRequest);
		mattel_pluck.setResultsCallback(setPhotoInfo);
		mattel_pluck.send();
	}

	return {
		'bind':           bind,
		'getTotalPhotos': getTotalPhotos
	};
}

Drupal.behaviors.pluck_photo_info = function(context) {
	if (typeof(mattel_pluck) != 'undefined') {
		if (typeof(photo_info) == 'undefined') {
			photo_info = new PluckPhotoInfo();
		}

		photo_info.bind(context);

		photo_info.getTotalPhotos($('.photo-info-total-photos', context));
	}
};
;
Drupal.behaviors.addToCart = function (context) { 

  // Updates the bag count on page load
  if($('#shopping-bag', context).length){
    $.getJSON(Drupal.settings.basePath + 'service/product/get-bag-count?ms=' + new Date().getTime(), function(data) {
      if (data) {
        updateBag(data.items, data.title);
      }
    });
  }
  
  $('form.accessory-attributes-form select').change(function() {
    var nid = $(this).val();
    
    if (nid && nid !== '0') {
      var price = $("option:selected", $(this)).attr('rel');
      if (price) {
        $(this).parents('.product-status').find('.sale-price').html('$' + price);
      }
    }
    
  });

  // Handles add to bag functionality
  $('a.add-to-cart', context).click(function() {

    if( $(this).hasClass('not_addable') || $(this).hasClass('processing') ) return false;
    
    var link     = $(this);
    var link_text = link.html();
    var nid       = $(this).attr('rel');
    
    if ($(this).parent('.message').parent('.product-status').find('form.accessory-attributes-form select').size()){
      nid = $(this).parent('.message').parent('.product-status').find('form.accessory-attributes-form select').val();
      
      if (!nid || nid == '0') {
        setAddMessage(link, {added: 0, message: "Please make a selection."});
      
        return false; // Stop now, don't continue processing as a selection has to be made first
      }
    }
    
    link.html('Adding item...');
    link.addClass('processing');

    $.getJSON(Drupal.settings.basePath + 'service/product/add-to-cart/' + nid, function(data, status) {
      if (data) {
        if (data.redirect) {
          window.location = data.redirect;
          return;
        }
        if (data.login) {
          var msg = '';
          if (data.message) {
            msg = data.message;
          }
          window.location = Drupal.settings.basePath + 'shop_login?redirect=' + encodeURIComponent(window.location.href) + '&msg=' + encodeURIComponent(msg) + '&req=add&nid=' + nid;
          return;
        }

        setAddMessage(link, data);

      }
      link.removeClass('processing');
      link.html(link_text);
    });
  });
  
  //Handles add to bag functionality

  if ($('a.add-collection-to-cart', context).length > 0 && $(".collection-item .accessory-attributes-form").length > 0) {
    $('a.add-collection-to-cart', context).remove();
  }
  $('a.add-collection-to-cart', context).click(function() {
    

    var link          = $(this);
    var link_text     = link.html();
    var collection_id = $(this).attr('rel');


    if ($(".collection-item .accessory-attributes-form", context).length > 0) {
     $('.collection-item a.add-to-cart').each(function (i, el) {
       $(el).click();
//       link.html('Added item:'+$(el).attr('rel'));
//      setAddMessage(link, {added: 1, message: $(el).attr('rel')});
      });
      setAddMessage(link, {added: 1, message: "Item(s) have been added to your bag."});
    }
    else {
      link.html('Adding item...');
      $.getJSON(Drupal.settings.basePath + 'service/product/add-collection-to-cart/' + collection_id, function(data, status) {
        if (data) {

          setAddMessage(link, data);
        }
        link.html(link_text);
      });
    }



  });
  
  //Handles add to bag functionality
  $('a.add-year-to-cart', context).click(function() {

    var link          = $(this);
    var link_text     = link.html();
    var year = $(this).attr('rel');

    link.html('Adding item...');

    $.getJSON(Drupal.settings.basePath + 'service/product/add-year-to-cart/' + year, function(data, status) {
      if (data) {

        setAddMessage(link, data);
      }
      link.html(link_text);
    });
  });  


}


// Update out shopping bag
var updateBag = function(bag_count, title) {

  var bag    = $('#shopping-bag');
  var counts = $('span.bag-count');
  bag_count  = parseInt(bag_count);
  
  if (isNaN(bag_count)) {
    bag_count = 0;
  }

  counts.html(bag_count);

  if(bag_count > 0 && $('#bag-link').length == 0) {
    bag.append('<span id="bag-link">' + Drupal.t('Checkout') + '</span>');
  }

  counts.parent().attr('title', title);

}

var setAddMessage = function(link, data) {
  if (data.items || data.added) {
    updateBag(data.items, data.title);
  }

  var message = $(document.createElement('div') );
  message.html(data.message);
  message.addClass('add-response');
  if (data.added > 0) {
    message.addClass('success');
    link.addClass('added');
  } else {
    message.addClass('fail');
    link.addClass('notadded');
  }
  message.css('display', 'none');
  link.after(message);
  message.fadeIn(500, function () {
    $(this).fadeOut(5000, function () {
      $(this).remove()
    })
  });
  

}
;
// $Id: extlink.js,v 1.4.2.12 2010/05/26 01:25:56 quicksketch Exp $
(function ($) {

function extlinkAttach(context) {
	try {
  // Strip the host name down, removing ports, subdomains, or www.
  var pattern = /^(([^\/:]+?\.)*)([^\.:]{4,})((\.[a-z]{1,4})*)(:[0-9]{1,5})?$/;
  var host = window.location.host.replace(pattern, '$3$4');
  var subdomain = window.location.host.replace(pattern, '$1');


  var subdomains = "([^/]*\\.)?";

  // Build regular expressions that define an internal link.
  var internal_link = new RegExp("^https?://" + subdomains + host, "i");

  var extInclude = false;
  var extExclude = false;

  // Find all links which are NOT internal and begin with http (as opposed
  // to ftp://, javascript:, etc. other kinds of links.
  // When operating on the 'this' variable, the host has been appended to
  // all links by the browser, even local ones.
  // In jQuery 1.1 and higher, we'd use a filter method here, but it is not
  // available in jQuery 1.0 (Drupal 5 default).
  var external_links = new Array();
  var mailto_links = new Array();
  $("a", context).each(function(el) {
    try {
      var url = this.href.toLowerCase();
      if ( url.indexOf('http') == 0 && (!url.match(internal_link)) ) {
        external_links.push(this);
      }
      else if (url.indexOf('mailto:') == 0) {
        mailto_links.push(this);
      }
    }
    // IE7 throws errors often when dealing with irregular links, such as:
    // <a href="node/10"></a> Empty tags.
    // <a href="http://user:pass@example.com">example</a> User:pass syntax.
    catch(error) {
      return false;
    }
  });

  $(external_links).attr('target', "_blank");

  // Work around for Internet Explorer box model problems.
  if (($.support && !($.support.boxModel === undefined) && !$.support.boxModel) || ($.browser.msie && parseInt($.browser.version) <= 7)) {
    $('span.ext, span.mailto').css('display', 'inline-block');
  }
  }
  catch (err) {}
}

Drupal.behaviors.extlink = function(context) {
  extlinkAttach(context);
}

})(jQuery);
;
$(document).ready(function() {
	$('a.mc_login').bind('click', popout);
});

function popout(e) {
	window.open(this.href, 'view', 'width=400,height=400');	
	
	return false;
};
/*
 * jQuery Tools 1.2.3 - The missing UI library for the Web
 * 
 * [scrollable, scrollable.navigator, overlay, toolbox.expose]
 * 
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 * 
 * http://flowplayer.org/tools/
 * 
 * File generated: Wed Jul 07 11:51:03 GMT 2010
 * Some changes have been made for barbiecollector (Scrollable plugin)
 */
(function(e){function n(f,c){var a=e(c);return a.length<2?a:f.parent().find(c)}function t(f,c){var a=this,l=f.add(a),g=f.children(),k=0,m=c.vertical;j||(j=a);if(g.length>1)g=e(c.items,f);e.extend(a,{getConf:function(){return c},getIndex:function(){return k},getSize:function(){return a.getItems().size()},getNaviButtons:function(){return o.add(p)},getRoot:function(){return f},getItemWrap:function(){return g},getItems:function(){return g.children(c.item).not("."+c.clonedClass)},move:function(b,d){return a.seekTo(k+
b,d)},next:function(b){return a.move(1,b)},prev:function(b){return a.move(-1,b)},begin:function(b){return a.seekTo(0,b)},end:function(b){return a.seekTo(a.getSize()-1,b)},focus:function(){return j=a},addItem:function(b){b=e(b);if(c.circular){e(".cloned:last").before(b);e(".cloned:first").replaceWith(b.clone().addClass(c.clonedClass))}else g.append(b);l.trigger("onAddItem",[b]);return a},seekTo:function(b,d,h){if(c.circular&&b===0&&k==-1&&d!==0)return a;if(!c.circular&&b<0||b>a.getSize()||b<-1)return a;
var i=b;if(b.jquery)b=a.getItems().index(b);else i=a.getItems().eq(b);var q=e.Event("onBeforeSeek");if(!h){l.trigger(q,[b,d]);if(q.isDefaultPrevented()||!i.length)return a}i=m?{top:-i.position().top}:{left:-i.position().left};k=b;j=a;if(d===undefined)d=c.speed;g.animate(i,d,c.easing,h||function(){l.trigger("onSeek",[b])});return a}});e.each(["onBeforeSeek","onSeek","onAddItem"],function(b,d){e.isFunction(c[d])&&e(a).bind(d,c[d]);a[d]=function(h){e(a).bind(d,h);return a}});if(c.circular){var r=a.getItems().slice(-1).clone().prependTo(g),
s=a.getItems().eq(1).clone().appendTo(g),moreclones=Math.ceil(g.parent().width()/r.width());for(var i=2; i<moreclones; i++){a.getItems().eq(i).clone().appendTo(g).addClass(c.clonedClass)};r.add(s).addClass(c.clonedClass);a.onBeforeSeek(function(b,d,h){if(!b.isDefaultPrevented())if(d==-1){a.seekTo(r,h,function(){a.end(0)});return b.preventDefault()}else d==a.getSize()&&a.seekTo(s,h,function(){a.begin(0)})});a.seekTo(0,0)}var o=n(f,c.prev).click(function(){a.prev()}),p=n(f,c.next).click(function(){a.next()});!c.circular&&a.getSize()>1&&a.onBeforeSeek(function(b,d){setTimeout(function(){if(!b.isDefaultPrevented()){o.toggleClass(c.disabledClass,
d<=0);p.toggleClass(c.disabledClass,d>=a.getSize()-1)}},1)});c.mousewheel&&e.fn.mousewheel&&f.mousewheel(function(b,d){if(c.mousewheel){a.move(d<0?1:-1,c.wheelSpeed||50);return false}});c.keyboard&&e(document).bind("keydown.scrollable",function(b){if(!(!c.keyboard||b.altKey||b.ctrlKey||e(b.target).is(":input")))if(!(c.keyboard!="static"&&j!=a)){var d=b.keyCode;if(m&&(d==38||d==40)){a.move(d==38?-1:1);return b.preventDefault()}if(!m&&(d==37||d==39)){a.move(d==37?-1:1);return b.preventDefault()}}});
e(a).trigger("onBeforeSeek",[c.initialIndex])}e.tools=e.tools||{version:"1.2.3"};e.tools.scrollable={conf:{activeClass:"active",circular:false,clonedClass:"cloned",disabledClass:"disabled",easing:"swing",initialIndex:0,item:null,items:".items",keyboard:true,mousewheel:false,next:".next",prev:".prev",speed:400,vertical:false,wheelSpeed:0}};var j;e.fn.scrollable=function(f){var c=this.data("scrollable");if(c)return c;f=e.extend({},e.tools.scrollable.conf,f);this.each(function(){c=new t(e(this),f);e(this).data("scrollable",
c)});return f.api?c:this}})(jQuery);
(function(d){function p(c,g){var h=d(g);return h.length<2?h:c.parent().find(g)}var m=d.tools.scrollable;m.navigator={conf:{navi:".navi",naviItem:null,activeClass:"active",indexed:false,idPrefix:null,history:false}};d.fn.navigator=function(c){if(typeof c=="string")c={navi:c};c=d.extend({},m.navigator.conf,c);var g;this.each(function(){function h(a,b,i){e.seekTo(b);if(j){if(location.hash)location.hash=a.attr("href").replace("#","")}else return i.preventDefault()}function f(){return k.find(c.naviItem||
"> *")}function n(a){var b=d("<"+(c.naviItem||"a")+"/>").click(function(i){h(d(this),a,i)}).attr("href","#"+a);a===0&&b.addClass(l);c.indexed&&b.text(a+1);c.idPrefix&&b.attr("id",c.idPrefix+a);return b.appendTo(k)}function o(a,b){a=f().eq(b.replace("#",""));a.length||(a=f().filter("[href="+b+"]"));a.click()}var e=d(this).data("scrollable"),k=p(e.getRoot(),c.navi),q=e.getNaviButtons(),l=c.activeClass,j=c.history&&d.fn.history;if(e)g=e;e.getNaviButtons=function(){return q.add(k)};f().length?f().each(function(a){d(this).click(function(b){h(d(this),
a,b)})}):d.each(e.getItems(),function(a){n(a)});e.onBeforeSeek(function(a,b){setTimeout(function(){if(!a.isDefaultPrevented()){var i=f().eq(b);!a.isDefaultPrevented()&&i.length&&f().removeClass(l).eq(b).addClass(l)}},1)});e.onAddItem(function(a,b){b=n(e.getItems().index(b));j&&b.history(o)});j&&f().history(o)});return c.api?g:this}})(jQuery);
(function(a){function t(d,b){var c=this,i=d.add(c),o=a(window),k,f,m,g=a.tools.expose&&(b.mask||b.expose),n=Math.random().toString().slice(10);if(g){if(typeof g=="string")g={color:g};g.closeOnClick=g.closeOnEsc=false}var p=b.target||d.attr("rel");f=p?a(p):d;if(!f.length)throw"Could not find Overlay: "+p;d&&d.index(f)==-1&&d.click(function(e){c.load(e);return e.preventDefault()});a.extend(c,{load:function(e){if(c.isOpened())return c;var h=q[b.effect];if(!h)throw'Overlay: cannot find effect : "'+b.effect+
'"';b.oneInstance&&a.each(s,function(){this.close(e)});e=e||a.Event();e.type="onBeforeLoad";i.trigger(e);if(e.isDefaultPrevented())return c;m=true;g&&a(f).expose(g);var j=b.top,r=b.left,u=f.outerWidth({margin:true}),v=f.outerHeight({margin:true});if(typeof j=="string")j=j=="center"?Math.max((o.height()-v)/2,0):parseInt(j,10)/100*o.height();if(r=="center")r=Math.max((o.width()-u)/2,0);h[0].call(c,{top:j,left:r},function(){if(m){e.type="onLoad";i.trigger(e)}});g&&b.closeOnClick&&a.mask.getMask().one("click",
c.close);b.closeOnClick&&a(document).bind("click."+n,function(l){a(l.target).parents(f).length||c.close(l)});b.closeOnEsc&&a(document).bind("keydown."+n,function(l){l.keyCode==27&&c.close(l)});return c},close:function(e){if(!c.isOpened())return c;e=e||a.Event();e.type="onBeforeClose";i.trigger(e);if(!e.isDefaultPrevented()){m=false;q[b.effect][1].call(c,function(){e.type="onClose";i.trigger(e)});a(document).unbind("click."+n).unbind("keydown."+n);g&&a.mask.close();return c}},getOverlay:function(){return f},
getTrigger:function(){return d},getClosers:function(){return k},isOpened:function(){return m},getConf:function(){return b}});a.each("onBeforeLoad,onStart,onLoad,onBeforeClose,onClose".split(","),function(e,h){a.isFunction(b[h])&&a(c).bind(h,b[h]);c[h]=function(j){a(c).bind(h,j);return c}});k=f.find(b.close||".close");if(!k.length&&!b.close){k=a('<a class="close"></a>');f.prepend(k)}k.click(function(e){c.close(e)});b.load&&c.load()}a.tools=a.tools||{version:"1.2.3"};a.tools.overlay={addEffect:function(d,
b,c){q[d]=[b,c]},conf:{close:null,closeOnClick:true,closeOnEsc:true,closeSpeed:"fast",effect:"default",fixed:!a.browser.msie||a.browser.version>6,left:"center",load:false,mask:null,oneInstance:true,speed:"normal",target:null,top:"10%"}};var s=[],q={};a.tools.overlay.addEffect("default",function(d,b){var c=this.getConf(),i=a(window);if(!c.fixed){d.top+=i.scrollTop();d.left+=i.scrollLeft()}d.position=c.fixed?"fixed":"absolute";this.getOverlay().css(d).fadeIn(c.speed,b)},function(d){this.getOverlay().fadeOut(this.getConf().closeSpeed,
d)});a.fn.overlay=function(d){var b=this.data("overlay");if(b)return b;if(a.isFunction(d))d={onBeforeLoad:d};d=a.extend(true,{},a.tools.overlay.conf,d);this.each(function(){b=new t(a(this),d);s.push(b);a(this).data("overlay",b)});return d.api?b:this}})(jQuery);
(function(b){function k(){if(b.browser.msie){var a=b(document).height(),d=b(window).height();return[window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,a-d<20?d:a]}return[b(document).width(),b(document).height()]}function h(a){if(a)return a.call(b.mask)}b.tools=b.tools||{version:"1.2.3"};var l;l=b.tools.expose={conf:{maskId:"exposeMask",loadSpeed:"slow",closeSpeed:"fast",closeOnClick:true,closeOnEsc:true,zIndex:9998,opacity:0.8,startOpacity:0,color:"#fff",onLoad:null,
onClose:null}};var c,i,f,g,j;b.mask={load:function(a,d){if(f)return this;if(typeof a=="string")a={color:a};a=a||g;g=a=b.extend(b.extend({},l.conf),a);c=b("#"+a.maskId);if(!c.length){c=b("<div/>").attr("id",a.maskId);b("body").append(c)}var m=k();c.css({position:"absolute",top:0,left:0,width:m[0],height:m[1],display:"none",opacity:a.startOpacity,zIndex:a.zIndex});a.color&&c.css("backgroundColor",a.color);if(h(a.onBeforeLoad)===false)return this;a.closeOnEsc&&b(document).bind("keydown.mask",function(e){e.keyCode==
27&&b.mask.close(e)});a.closeOnClick&&c.bind("click.mask",function(e){b.mask.close(e)});b(window).bind("resize.mask",function(){b.mask.fit()});if(d&&d.length){j=d.eq(0).css("zIndex");b.each(d,function(){var e=b(this);/relative|absolute|fixed/i.test(e.css("position"))||e.css("position","relative")});i=d.css({zIndex:Math.max(a.zIndex+1,j=="auto"?0:j)})}c.css({display:"block"}).fadeTo(a.loadSpeed,a.opacity,function(){b.mask.fit();h(a.onLoad)});f=true;return this},close:function(){if(f){if(h(g.onBeforeClose)===
false)return this;c.fadeOut(g.closeSpeed,function(){h(g.onClose);i&&i.css({zIndex:j})});b(document).unbind("keydown.mask");c.unbind("click.mask");b(window).unbind("resize.mask");f=false}return this},fit:function(){if(f){var a=k();c.css({width:a[0],height:a[1]})}},getMask:function(){return c},isLoaded:function(){return f},getConf:function(){return g},getExposed:function(){return i}};b.fn.mask=function(a){b.mask.load(a);return this};b.fn.expose=function(a){b.mask.load(a,this);return this}})(jQuery);
;
$(function() {
  var wrapoverlay;
  var registrationok = false;
  var wrap;
  var overlay;

  function forceHttps(action) {
    if (action.substring(0, 5) != 'https') {
      if (action.substring(0, 4) == 'http') {
        action = 'https' + action.substring(4);
      }
      else {
        action = 'https://' + document.location.hostname + action;
      }
    }
    return action;
  }

  function loadregister(){
    wrap.load('/ajax/bc-user/register',function(){
      Drupal.attachBehaviors($(this));
      var form = $('form', this);
      var action = forceHttps($(form).attr('action'));
      action = action.replace("ajax/bc-user", "user"); // we want this to submit and redirect to the real user/register page
      $(form).attr('action', action);
    });
    return false;
  }

  /* Overlay */
  $("a.loginlink").click(function(){
    var toregister = ( $(this).attr('href').indexOf('user/register') != -1)  ? true : false;
    // Add the overlay div
    wrapoverlay = $('<div id="log_reg_overlay"><a id="close-bouton" class="close"></a><div class="contentWrap"></div></div>').appendTo( $('body') );

    overlay = wrapoverlay.overlay({
      fixed:false,
      load:true,
      mask: {
        color: '#000',
        loadSpeed: 0,
        closeSpeed: 0,
        startOpacity: 0.4,
        opacity: 0.6
        }, 
      onBeforeLoad: function() {
        wrap = this.getOverlay().find(".contentWrap");
        if(toregister) {
          loadregister();
        }
        else {
          wrap.load('/ajax/bc-user/login?redirect=' + encodeURIComponent(document.location.href), function(){
            Drupal.attachBehaviors($(this));
            $('#edit-name', $(this)).focus();
            form = $('form', this);
            action = forceHttps($(form).attr('action'));
            $(form).attr('action', action);
          })
        }
      },
      onClose : function() {
        wrapoverlay.remove();
      }
    });
    return false;
  });

  $('#log_reg_overlay a.close-window').live('click', function(){
    overlay.data('overlay').close();
    return false;
  });

  /* Registration */
  $('#log_reg_overlay #reg-link a').live('click', loadregister);
});


;
$(function() {

  var $panel   = $('#bc_shell-primary_navigation .view-id-masthead_panel');
  var $trigger = $('#browse-catalog');

  $trigger.bind('mouseenter', function(e) {
    e.stopPropagation();
    $panel.fadeIn();
    $(this).removeClass('closed').addClass('opened');
    if ($(".prod-img img", $panel).hasClass('ondemand')) {
      replacePlaceHolderImgInView($panel);
    }
  });

  $('div.browse-catalog-wrapper').bind('mouseleave', function(e) {
    e.stopPropagation();
    $panel.fadeOut();
    $trigger.removeClass('opened').removeClass('hold').addClass('closed');
  });

});
$(document).ready(function(){
  $(".menu-shopcategory li a").each(function (i, e) {
    var group_name = $(e).attr('rel');

    $(e).hover(function () {
      toggleMenuListItems(group_name, true); // show it
    }, function () {
      toggleMenuListItems(group_name, false); // hide it
    });
  });

  var prevLeftShop = 0;
  var prevLeftShowcase = 0;
  if ($.browser.msie) {
    $('ul#primary li#menu-primary-shop').hover(function () {
      prevLeftShop = $("ul.menu-shopcategory", $(this)).css('left');
      $("ul.menu-shopcategory", $(this)).css('left', 0);
      $("ul.menu-shopcategory", $(this)).addClass('opened');
    }, function () {
      $("ul.menu-shopcategory", $(this)).css('left', prevLeftShop);
      $("ul.menu-shopcategory", $(this)).removeClass('opened');
    });

    $('ul#primary li#menu-primary-showcase').hover(function () {
      prevLeftShowcase = $("ul#primary li#menu-primary-showcase ul", $(this)).css('left');
      $("ul#primary li#menu-primary-showcase ul", $(this)).css('left', 0);
      $("ul#primary li#menu-primary-showcase ul", $(this)).addClass('opened');
    }, function () {
      $("ul#primary li#menu-primary-showcase ul", $(this)).css('left', prevLeftShowcase);
      $("ul#primary li#menu-primary-showcase ul", $(this)).removeClass('opened');
    });
  }

});

function toggleMenuListItems(group_name, show) {
  if (show) {
    $(".menu-shopcategory ."+group_name+'.parent').addClass('opened'); // hide if none in the group is active
    $(".menu-shopcategory ."+group_name+'.parent').removeClass('closed'); // hide if none in the group is active
    $(".menu-shopcategory ."+group_name).removeClass('hidden');
  } else {
    $(".menu-shopcategory ."+group_name+'.parent').removeClass('opened'); // hide if none in the group is active
    $(".menu-shopcategory ."+group_name+'.parent').addClass('closed'); // hide if none in the group is active
    $(".menu-shopcategory ."+group_name+'.child').addClass('hidden'); // hide if none in the group is active
  }
};
$(document).ready(function(){
  $('#archives_news_navigation').children().hide();
  $('#archives_news_navigation div').hide();
  
  $('#archives_news_navigation > li > a').click(function(){
    if($(this).hasClass('expend')){
      $(this).removeClass('expend').parent().find('div').hide('fast');
    } else {
      $('.expend').removeClass('expend').parent().find('div').hide('fast');
      $(this).addClass('expend').parent().find('div').show('fast');
    }
    return false;
  })
   
   $('<div class="ui-more"><a href="#">' + Drupal.t('more') + '</a></div>').prependTo($('#archives_news_navigation')).click(function(){
       $(this).remove();
       $('#archives_news_navigation').children().show('fast');
       return false;
   })

});
/*
 * Viewport - jQuery selectors for finding elements in viewport
 *
 * Copyright (c) 2008-2009 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *  http://www.appelsiini.net/projects/viewport
 *
 */
(function($) {

    $.belowthefold = function(element, settings) {
        var fold = $(window).height() + $(window).scrollTop();
        return fold <= $(element).offset().top - settings.threshold;
    };

    $.abovethetop = function(element, settings) {
        var top = $(window).scrollTop();
        return top >= $(element).offset().top + $(element).height() - settings.threshold;
    };

    $.rightofscreen = function(element, settings) {
        var fold = $(window).width() + $(window).scrollLeft();
        return fold <= $(element).offset().left - settings.threshold;
    };

    $.leftofscreen = function(element, settings) {
        var left = $(window).scrollLeft();
        return left >= $(element).offset().left + $(element).width() - settings.threshold;
    };

    $.inviewport = function(element, settings) {
        var $element = $(element);
        var offset = $element.offset();

        var $window = $(window);
        var windowTop = $window.scrollTop();
        var threshold = settings.threshold;

        if (offset.top - threshold < windowTop) {
            if (offset.top + $element.height() + threshold >= windowTop) {
                // top edge below the window's top
            } else {
                return false;
            }
        } else {
            if (offset.top - threshold <= windowTop + $window.height()) {
                // bottom edge above the window's bottom
            } else {
                return false;
            }
        }

        var windowLeft = $window.scrollLeft();

        if (offset.left - threshold < windowLeft) {
            if (offset.left + $element.width() + threshold >= windowLeft) {
                // left edge be on the left side of the window's left edge
            } else {
                return false;
            }
        } else {
            if (offset.left - threshold <= windowLeft + $window.width()) {
                // right edge be on the right side of the window's right edge
            } else {
                return false;
            }
        }

        return true;
    };

    $.extend($.expr[':'], {
        "below-the-fold": function(a, i, m) {
            return $.belowthefold(a, {threshold : 0});
        },
        "above-the-top": function(a, i, m) {
            return $.abovethetop(a, {threshold : 0});
        },
        "left-of-screen": function(a, i, m) {
            return $.leftofscreen(a, {threshold : 0});
        },
        "right-of-screen": function(a, i, m) {
            return $.rightofscreen(a, {threshold : 0});
        },
        "in-viewport": function(a, i, m) {
            return $.inviewport(a, {threshold : 0});
        }
    });


})(jQuery);;
var replacePlaceHolderImgInView = function (container) {
  var imgs = container == false ? $("img.ondemand:in-viewport") : $("img.ondemand:in-viewport", container);

  imgs.each(function(i,e) {
    var img = $(this);
    var exclude = false;
//    for (var i = 0; i < Drupal.settings.bc_shop.exclude_elements.length; i++) {
//      if (img.parents(Drupal.settings.bc_shop.exclude_elements[i]).length > 0) {
//        exclude = true;
//      }
//    }
    if (!exclude) {
      img.attr('src', img.attr('longdesc')).removeClass('ondemand');
    }
  });
}
$(function() {
  $(window).scroll(function() {
    replacePlaceHolderImgInView(false);
  });
});
Drupal.behaviors.imgOndemand = function(context) {
  replacePlaceHolderImgInView(context);
};;
$(function() {

  var recently_viewed = new BCShopRecentlyViewed();
  recently_viewed.init();

});

// Callback function from Ajax request
function _authcache_recently_viewed(vars) {
  $('h3', $('.footer #bc_shop-dollicious')).html(Drupal.t("You've Recently Viewed"));
  $('div.content', $('.footer #bc_shop-dollicious')).html(vars);

  $('.footer #bc_shop-dollicious').attr('id', 'bc_shop-recently_viewed');
  
  Drupal.attachBehaviors('#bc_shop-recently_viewed');
}


var BCShopRecentlyViewed = function() {
  var jsonurl = '/shop/ajax/recently_viewed';
  var $block = $('.footer #bc_shop-dollicious');
  var nids = null;

  function init() {
    nids = getCookie('bc_shop_recently_viewed');

    if (nids && $block.size() > 0) {
      if (typeof(Authcache) == 'undefined' || !Authcache.isEnabled) {
        $.get(jsonurl+'/'+nids+'?link_destination='+window.location, function (data) {
          _authcache_recently_viewed(data);
        });
      }
      else {
        // Perform independent Authcache ajax request
        Authcache.ajaxRequest({
          // The name of the function to call, both for ajax_authcache.php and
          // this file (see function above). The cookie value will change if
          // the user updates their block (used for max_age cache invalidation)
          'recently_viewed' : nids,

          'q': Authcache.ajax.q,
      
          // Makes browser cache the Ajax response to help reduce server resources
          'max_age' : 3600
        });
      }
    }
  }
  
  function setCookie(c_name,value,exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays==null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
  }
  
  function getCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0; i< ARRcookies.length; i++) {
      x = ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
      y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
      x = x.replace(/^\s+|\s+$/g,"");

      if (x == c_name) {
        return unescape(y);
      }
    }
    
    return false;
  }
  
  return {
		'init': init
	};
}


;
Drupal.behaviors.overlayWishlist = function(context) {
  var hideShowOverlay = function (overlay, overlayContainer) {
    overlay.css('opacity', 0);
    overlayContainer.mouseenter(function(ev) {
      overlay.stop(true);
      overlay.fadeTo(400, 1);
    });
    overlayContainer.mouseleave(function(ev) {
      overlay.stop(true);
      overlay.fadeTo(400, 0, function(ev) {
      });
    });

  }
  $('div.overlay-wishlist', context).each(function(i, el) {
    var overlay = $(el);
//    if (overlay.hasClass('auto')) {
//      hideShowOverlay(overlay, overlay.parent());
//    } else {
      hideShowOverlay($('.bc-wishlist-flag-wrapper', overlay), overlay.parent());
//    }
  });
}
;
// $Id: flag.js,v 1.1.2.7.2.5 2010/05/08 23:48:54 quicksketch Exp $

/**
 * Terminology:
 *
 *   "Link" means "Everything which is in flag.tpl.php" --and this may contain
 *   much more than the <A> element. On the other hand, when we speak
 *   specifically of the <A> element, we say "element" or "the <A> element".
 */

/**
 * The main behavior to perform AJAX toggling of links.
 */
Drupal.flagLink = function(context) {
  /**
   * Helper function. Updates a link's HTML with a new one.
   *
   * @param element
   *   The <A> element.
   * @return
   *   The new link.
   */
  function updateLink(element, newHtml) {
    var $newLink = $(newHtml);

    // Initially hide the message so we can fade it in.
    $('.flag-message', $newLink).css('display', 'none');

    // Reattach the behavior to the new <A> element. This element
    // is either whithin the wrapper or it is the outer element itself.
    var $nucleus = $newLink.is('a') ? $newLink : $('a.flag', $newLink);
    $nucleus.addClass('flag-processed').click(flagClick);

    // Find the wrapper of the old link.
    var $wrapper = $(element).parents('.flag-wrapper:first');
    if ($wrapper.length == 0) {
      // If no ancestor wrapper was found, or if the 'flag-wrapper' class is
      // attached to the <a> element itself, then take the element itself.
      $wrapper = $(element);
    }
    // Replace the old link with the new one.
    $wrapper.after($newLink).remove();
    Drupal.attachBehaviors($newLink.get(0));

    $('.flag-message', $newLink).fadeIn();
    setTimeout(function(){ $('.flag-message', $newLink).fadeOut() }, 3000);
    return $newLink.get(0);
  }

  /**
   * A click handler that is attached to all <A class="flag"> elements.
   */
  function flagClick() {
    // 'this' won't point to the element when it's inside the ajax closures,
    // so we reference it using a variable.
    var element = this;

    // While waiting for a server response, the wrapper will have a
    // 'flag-waiting' class. Themers are thus able to style the link
    // differently, e.g., by displaying a throbber.
    var $wrapper = $(element).parents('.flag-wrapper');
    if ($wrapper.is('.flag-waiting')) {
      // Guard against double-clicks.
      return false;
    }
    $wrapper.addClass('flag-waiting');

    // Hide any other active messages.
    $('span.flag-message:visible').fadeOut();

    // Send POST request
    $.ajax({
      type: 'POST',
      url: element.href,
      data: { js: true },
      dataType: 'json',
      success: function (data) {
        if (data.status) {
          // Success.
          data.link = $wrapper.get(0);
          $.event.trigger('flagGlobalBeforeLinkUpdate', [data]);
          if (!data.preventDefault) { // A handler may cancel updating the link.
            data.link = updateLink(element, data.newLink);
          }
          $.event.trigger('flagGlobalAfterLinkUpdate', [data]);
        }
        else {
          // Failure.
          alert(data.errorMessage);
          $wrapper.removeClass('flag-waiting');
        }
      },
      error: function (xmlhttp) {
        alert('An HTTP error '+ xmlhttp.status +' occurred.\n'+ element.href);
        $wrapper.removeClass('flag-waiting');
      }
    });
    return false;
  }

  $('a.flag-link-toggle:not(.flag-processed)', context).addClass('flag-processed').click(flagClick);
};

/**
 * Prevent anonymous flagging unless the user has JavaScript enabled.
 */
Drupal.flagAnonymousLinks = function(context) {
  $('a.flag:not(.flag-anonymous-processed)', context).each(function() {
    this.href += (this.href.match(/\?/) ? '&' : '?') + 'has_js=1';
    $(this).addClass('flag-anonymous-processed');
  });
}

/**
 * A behavior specifically for anonymous users. Update links to the proper state.
 */
Drupal.flagAnonymousLinkTemplates = function(context) {
  // Swap in current links. Cookies are set by PHP's setcookie() upon flagging.

  // Build a list of user-flags.
  var userFlags = Drupal.flagCookie('flags');
  if (userFlags) {
    userFlags = userFlags.split('+');
    $.each(userFlags, function (n, value) {
      var flagInfo = userFlags[n].split('_');
      var flagName = flagInfo[0];
      var contentId = flagInfo[1];
      // User flags always default to off and the JavaScript toggles them on.
      $('.flag-' + flagName + '-' + contentId, context).after(Drupal.settings.flag.templates[flagName + '_' + contentId]).remove();
    });
  }

  // Build a list of global flags.
  var globalFlags = document.cookie.match(/flag_global_([a-z0-9\-]+)_([0-9]+)=([01])/ig);
  if (globalFlags) {
    for (var n in globalFlags) {
      var flagInfo = globalFlags[n].match(/flag_global_([a-z0-9\-]+)_([0-9]+)=([01])/i);
      var flagName = flagInfo[1];
      var contentId = flagInfo[2];
      var flagState = (flagInfo[3] == '1') ? 'flag' : 'unflag';
      // Global flags are tricky, they may or may not be flagged in the page
      // cache. The template always contains the opposite of the current state.
      // So when checking global flag cookies, we need to make sure that we
      // don't swap out the link when it's already in the correct state.
      $('.flag-' + flagName + '-' + contentId, context).each(function() {
        if ($(this).find('.' + flagState + '-action').size()) {
          $(this).after(Drupal.settings.flag.templates[flagName + '_' + contentId]).remove();
        }
      });
    }
  }
}

/**
 * Utility function used to set Flag cookies.
 *
 * Note this is a direct copy of the jQuery cookie library.
 * Written by Klaus Hartl.
 */
Drupal.flagCookie = function(name, value, options) {
  if (typeof value != 'undefined') { // name and value given, set cookie
    options = options || {};
    if (value === null) {
      value = '';
      options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
      options.expires = -1;
    }
    var expires = '';
    if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
      var date;
      if (typeof options.expires == 'number') {
        date = new Date();
        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
      } else {
        date = options.expires;
      }
      expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
    }
    // NOTE Needed to parenthesize options.path and options.domain
    // in the following expressions, otherwise they evaluate to undefined
    // in the packed version for some reason...
    var path = options.path ? '; path=' + (options.path) : '';
    var domain = options.domain ? '; domain=' + (options.domain) : '';
    var secure = options.secure ? '; secure' : '';
    document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
  } else { // only name given, get cookie
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }
};

Drupal.behaviors.flagLink = function(context) {
  // For all anonymous users, require JavaScript for flagging to prevent spiders
  // from flagging things inadvertently.
  if (Drupal.settings.flag && Drupal.settings.flag.anonymous) {
    Drupal.flagAnonymousLinks(context);
  }

  // For anonymous users with the page cache enabled, swap out links with their
  // current state for the user.
  if (Drupal.settings.flag && Drupal.settings.flag.templates) {
    Drupal.flagAnonymousLinkTemplates(context);
  }

  // On load, bind the click behavior for all links on the page.
  Drupal.flagLink(context);
};
;
var replacePlaceHolderImgOnSlide = function (container) {
//  replacePlaceHolderImgInView(container);
  $("img.ondemand", container).each(function(i,e) {
    $(this).attr('src', $(this).attr('longdesc')).removeClass('ondemand');
  });
}

Drupal.behaviors.scrollable = function(context) {
  var init = function() {
    $('.scrollable', context).each(function(i, scrollElement) {
      var scroller = $(scrollElement), container;
      var page = $('div.scrollable-page:first', scroller);
      var settings = retrieveInstanceSettings(scroller);
      scroller.width(settings.width == 'auto' ? page.width() : settings.width);
      scroller.height(settings.height == 'auto' ? page.height() + 3 : settings.height + 3);
      if (settings.navigator) {
        var navi = $('<div></div>').addClass('navi').insertBefore(scroller);
        container = scroller.scrollable(settings).navigator();
        navi.css('width', navi.find('a').size() * 14);
      }
       else {
        container = scroller.scrollable(settings);
      }
      
      if ($('.scrollable-page', scroller).length < 2) {
        // Perhaps we should explicitly hide them?  Same difference right now...
        $('a.browse', scroller.parent()).addClass('disabled');
        replacePlaceHolderImgOnSlide(scroller);
      }
      replacePlaceHolderImgOnSlide(page.addClass('scurrent'));
      $('a.browse', scroller.parent()).click(function () {
        var cur_page = $(".scurrent", scroller);
        var nex_page = false;
        if ($(this).hasClass("next")) {
          nex_page = cur_page.next();
        } else {
          nex_page = cur_page.prev();
        }
        cur_page.removeClass('scurrent');
        nex_page.addClass('scurrent');
        replacePlaceHolderImgOnSlide(nex_page);
      });
      Drupal.attachBehaviors( $('.cloned', container) );
    }).addClass('scrollable-processed');
  }
    
  var retrieveInstanceSettings = function($el) {
    var classes = $el.parent().attr('class').split(' ');
    var reg = /^scrollable-container-\d+$/;
    var classId,i;
    
    for (i in classes) {
      if (reg.test(classes[i])) {
        classId = classes[i];
        break;
      }
    }
    
    if (!classId) {
      return false;
    }
    
    // else...
    //console.log(Drupal.settings.scrollable[classId]);
    return Drupal.settings.scrollable[classId];
  }
  
  init();
};
var PluckPhoto = function(photoRegion) {
	// General pluck configurations
	var pluckUrl = Drupal.settings.mattel_pluck.url;
	var baseUrl = Drupal.settings.mattel_pluck.base_url;
	var pluckUserPrefix = Drupal.settings.mattel_pluck.user_prefix;
	var pluckContentPrefix = Drupal.settings.mattel_pluck.content_prefix;

	// General photo region setup
	var customKey = photoRegion.attr('customKey');
	var photoContentTotalItems = null;
	var photoContentPage = null;
	var photoContentTotalPages = null;
	var photoContentPerPage = null;

	var photoContentRegion = photoRegion.find('.pluck-photo-single');
	var photoGalleryRegion = photoRegion.find('.pluck-photo-gallery');
	var photoAlternativeRegion = photoRegion.find('.pluck-photo-alternative');

	var photoContentPhotoKey = null;
	var photoList = [];
	var sortMethod = new PluckSDK.TimestampSort();
	sortMethod.SortOrder = PluckSDK.SortEnum.TimeStampDescending;

	function _bindGalleryRegion() {
/*
		var options = {
			'TimeStampDescending': Drupal.t('Recent photos'),
			'RatingDescending':    Drupal.t('Highest Rated')
		};
		for (var option in options) {
			photoGalleryRegion.find('.pluck-photo-order-select').append('<option value="' + option + '">' + options[option] + '</option>');
		}

		photoGalleryRegion.find('.pluck-photo-order-select').change(function () {
			if (this.value == 'TimeStampDescending') {
				sortMethod = new PluckSDK.TimestampSort();
				sortMethod.SortOrder = PluckSDK.SortEnum.TimeStampDescending;
			}
			else if (this.value == 'RatingDescending') {
				sortMethod = new PluckSDK.AlphabeticalSort();
				sortMethod.SortOrder = PluckSDK.SortEnum.RatingDescending;
			}

			_getGalleryPhotos();
		});
*/

		photoGalleryRegion.find('.pluck-photo-pager-prev').click(function () {
			if (photoContentPage > 1) {
				photoContentPage = photoContentPage - 1;
				_getGalleryPhotos();
			}
		});
		photoGalleryRegion.find('.pluck-photo-pager-next').click(function () {
			if (photoContentPage < photoContentTotalPages) {
				photoContentPage = photoContentPage + 1;
				_getGalleryPhotos();
			}
		});
	}

	function _getSinglePhoto() {
		if (photoContentPhotoKey) {
			var photoRequest = new PluckSDK.PhotoRequest();
			photoRequest.PhotoKey = new PluckSDK.PhotoKey();
			photoRequest.PhotoKey.Key = photoContentPhotoKey;

			mattel_pluck.queue(photoRequest);
			mattel_pluck.setResultsCallback(_handleSinglePhotoResponse);
		}
		else {
			photoContentPage = (photoContentPage) ? photoContentPage : 1;

			var customCollectionsPageRequest = new PluckSDK.CustomCollectionsPageRequest();
			customCollectionsPageRequest.CustomCollectionKey = new PluckSDK.CustomCollectionKey();
			customCollectionsPageRequest.CustomCollectionKey.Key = customKey;
			customCollectionsPageRequest.ItemsPerPage = 1;
			customCollectionsPageRequest.OneBasedOnPage = photoContentPage;
			customCollectionsPageRequest.Sort = sortMethod;

			mattel_pluck.queue(customCollectionsPageRequest);
			mattel_pluck.setResultsCallback(_handleSinglePhotoCollectionResponse);
		}

		mattel_pluck.send();
	}

	function _getGalleryInfo(callback, customKeyOveride) {
		var customCollectionsPageRequest = new PluckSDK.CustomCollectionsPageRequest();
		customCollectionsPageRequest.CustomCollectionKey = new PluckSDK.CustomCollectionKey();
		customCollectionsPageRequest.CustomCollectionKey.Key = (typeof(customKeyOveride) != 'undefined') ? customKeyOveride : customKey;
		customCollectionsPageRequest.OneBasedOnPage = 0;

		mattel_pluck.queue(customCollectionsPageRequest);
		mattel_pluck.setResultsCallback(callback);
		mattel_pluck.send();
	}

	function _getSelectionGallery() {
		var customCollectionsPageRequest = new PluckSDK.CustomCollectionsPageRequest();
		customCollectionsPageRequest.CustomCollectionKey = new PluckSDK.CustomCollectionKey();
		customCollectionsPageRequest.CustomCollectionKey.Key = customKey;
		customCollectionsPageRequest.ItemsPerPage = photoContentTotalItems;
		customCollectionsPageRequest.OneBasedOnPage = 1;
		customCollectionsPageRequest.Sort = sortMethod;

		mattel_pluck.queue(customCollectionsPageRequest);
		mattel_pluck.setResultsCallback(_loadSelectionGallery);
		mattel_pluck.send();
	}

	function _getGalleryPhotos() {
		var customCollectionsPageRequest = new PluckSDK.CustomCollectionsPageRequest();
		customCollectionsPageRequest.CustomCollectionKey = new PluckSDK.CustomCollectionKey();
		customCollectionsPageRequest.CustomCollectionKey.Key = customKey;
		customCollectionsPageRequest.ItemsPerPage = photoContentPerPage;
		customCollectionsPageRequest.OneBasedOnPage = photoContentPage;
		customCollectionsPageRequest.Sort = sortMethod;

		mattel_pluck.queue(customCollectionsPageRequest);
		mattel_pluck.setResultsCallback(_loadGalleryPhotos);
		mattel_pluck.send();
	}

	function _getOverlay(userCustomKey) {
		var photoRequest = new PluckSDK.PhotoRequest();
		photoRequest.PhotoKey = new PluckSDK.PhotoKey();
		photoRequest.PhotoKey.Key = photoContentPhotoKey;

		mattel_pluck.queue(photoRequest);

		var customCollectionsPageRequest = new PluckSDK.CustomCollectionsPageRequest();
		customCollectionsPageRequest.CustomCollectionKey = new PluckSDK.CustomCollectionKey();
		customCollectionsPageRequest.CustomCollectionKey.Key = userCustomKey;
		customCollectionsPageRequest.OneBasedOnPage = 0;

		mattel_pluck.queue(customCollectionsPageRequest);

		mattel_pluck.setResultsCallback(_loadOverlay);
		mattel_pluck.send();
	}

	function _handleSinglePhotoResponse(responses) {
		if (responses[0].ResponseStatus.StatusCode != PluckSDK.ResponseStatusCode.OK) {
			photoAlternativeRegion.show();
		}
		else {
			var photo = responses[0].Photo;
			var prefix = pluckContentPrefix + 'user_';
			var isOwn = false;

			if (customKey.search(prefix) != -1) {
				pluckUser = customKey.substr(prefix.length);
				isOwn = (pluckUser == photo.Owner.UserKey.Key);
			}

			if (isOwn || photo.Tags.indexOf(customKey) != -1) {
				photoContentRegion.show();

				_loadSinglePhoto(photo);
			}
			else {
				photoAlternativeRegion.show();
			}
		}
	}

	function _handleSinglePhotoCollectionResponse(responses) {
		if (responses[0].ResponseStatus.StatusCode != PluckSDK.ResponseStatusCode.OK) {
			photoAlternativeRegion.show();
		}
		else {
			if (responses[0].Items.length == 1 && responses[0].Items[0].ObjectType == 'Models.Media.Photo') {
				photoContentRegion.show();

				photoContentPage = responses[0].OneBasedOnPage;
				photoContentTotalItems = responses[0].TotalItems;
				photoContentTotalPages = photoContentTotalItems;

				var leftArrow = (photoContentPage > 1) ? '<span class="pluck-photo-content-prev">prev</span>' : '';
				var rightArrow = (photoContentPage < photoContentTotalPages) ? '<span class="pluck-photo-content-next">next</span>' : '';

				_loadSinglePhoto(responses[0].Items[0], leftArrow, rightArrow);
			}
			else {
				photoAlternativeRegion.show();
			}
		}
	}

	function _loadSinglePhoto(photo, leftArrow, rightArrow) {
		leftArrow = (typeof(leftArrow) != 'undefined') ? leftArrow : '';
		rightArrow = (typeof(rightArrow) != 'undefined') ? rightArrow : '';
		var preset;
		if (photoContentRegion.find('.pluck-photo').attr('preset')) {
			preset = photoContentRegion.find('.pluck-photo').attr('preset');
		}
		var user = photo.Owner.UserKey.Key;
		user = user.substr(pluckUserPrefix.length);
		photoContentRegion.find('.pluck-photo').html(leftArrow + '<div class="photo-single"><img src="' + mattel_pluck.getImageUrl(photo.Image.Full, preset) + '" /></div>' + rightArrow);
		if (photo.PhotoKey.Key != photoContentPhotoKey) {
			photoContentRegion.find('.pluck-photo img').click(function () {
				window.location.assign(baseUrl + '/user/' + user + '/photos/' + photo.PhotoKey.Key + '#user-photo');
			});
		}
		photoContentRegion.find('.pluck-photo .pluck-photo-content-prev').click(function () {
			photoContentPage--;
			_getSinglePhoto();
		});
		photoContentRegion.find('.pluck-photo .pluck-photo-content-next').click(function () {
			photoContentPage++;
			_getSinglePhoto();
		});

		photoContentRegion.find('.pluck-photo-title').text(photo.Title);
		photoContentRegion.find('.pluck-photo-description').text(photo.Description);
		if (photoContentPhotoKey) {
			photoContentRegion.find('.pluck-photo-comments').html('<pas:pluck_comments ' + Drupal.settings.mattel_pluck.params_str + ' plckDiscoverySection="'+ pluckContentPrefix +'site"  plckDiscoveryCategories="' + pluckContentPrefix + 'comments" plckCommentOnKeyType="photo" plckCommentOnKey="' + photoContentPhotoKey + '"></pas:pluck_comments>');
			pluckAppProxy.replaceTag("pluck_comments");
		}

		if (photoContentRegion.find('.pluck-photo-in-photo').length) {
			var products = _getValuesFromTagsWithPrefix(photo.Tags, pluckContentPrefix + 'product_');
			_getPhotoInPhotoRegion(products);
		}
		if (photoContentRegion.find('.pluck-photo-info').length) {
			_getPhotoInfoRegion(user, photo.CreatedOn);
		}
	}

	function _loadSelectionGalleryFromInfo(responses) {
		if (responses[0].ResponseStatus.StatusCode != PluckSDK.ResponseStatusCode.OK) {
			photoAlternativeRegion.show();
		}
		else {
			photoContentPage = 1;
			photoContentTotalItems = responses[0].TotalItems;
			photoContentTotalPages = Math.ceil(photoContentTotalItems / photoContentPerPage);

			_getSelectionGallery();
		}
	}

	function _loadSelectionGallery(responses) {
		if (responses[0].ResponseStatus.StatusCode != PluckSDK.ResponseStatusCode.OK) {
			photoAlternativeRegion.show();
		}
		else {
			if (responses[0].Items.length > 0 && responses[0].Items[0].ObjectType == 'Models.Media.Photo') {
				photoList = responses[0].Items;

				_getSinglePhotoPagers();

				_populateSelectionGallery();
				_getPhotoPageInfo(photoContentRegion.find('.pluck-photo-page-info'));
			}
		}
	}

	function _loadGalleryPhotos(responses) {
		if (responses[0].ResponseStatus.StatusCode != PluckSDK.ResponseStatusCode.OK) {
			photoAlternativeRegion.show();
		}
		else {
			if (responses[0].Items.length > 0 && responses[0].Items[0].ObjectType == 'Models.Media.Photo') {
				photoContentTotalItems = responses[0].TotalItems;
				photoContentTotalPages = Math.ceil(photoContentTotalItems / photoContentPerPage);

				if (photoGalleryRegion.find('.pluck-photo-page-info').length) {
					_getPhotoPageInfo(photoGalleryRegion.find('.pluck-photo-page-info'));
				}

				photoGalleryRegion.show();
				photoGalleryRegion.find('.pluck-photo-selection-gallery').html('');

				if (photoContentPage > 1) {
					photoGalleryRegion.find('.pluck-photo-pager-prev').show();
					if (photoGalleryRegion.find('.pluck-photo-selection-gallery').hasClass('pluck-photo-pageable')) {
						photoGalleryRegion.find('.pluck-photo-selection-gallery').append('<li class="pluck-photo-gallery-prev">prev</li>');
					}
				}
				else {
					photoGalleryRegion.find('.pluck-photo-pager-prev').hide();
				}

				$.each(responses[0].Items, function (i, photo) {
					var key = photo.PhotoKey.Key;
					var user = photo.Owner.UserKey.Key;
					user = user.substr(pluckUserPrefix.length);
					var userCustomKey = pluckContentPrefix + 'user_' + pluckUserPrefix + user;
					var preset;
					if (photoGalleryRegion.find('.pluck-photo-selection-gallery').attr('preset')) {
						preset = photoGalleryRegion.find('.pluck-photo-selection-gallery').attr('preset');
					}

					if (photoGalleryRegion.find('.pluck-photo-selection-gallery').hasClass('pluck-photo-num-comments')) {
						var title = photo.Title;
						title = (title.length > 40) ? title.substr(0, 37) + '...' : title;
						photoGalleryRegion.find('.pluck-photo-selection-gallery').append('<li class="pluck-photo-gallery-item" id="' + key + '" user="' + user + '"><img src="' + mattel_pluck.getImageUrl(photo.Image.Full, preset) + '" /><div class="photo-info"><span class="pluck-photo-title">' + title + '</span><span class="pluck-photo-comment-count"></span></li>');

						var commentsPageRequest = new PluckSDK.CommentsPageRequest();
						commentsPageRequest.CommentedOnKey = new PluckSDK.PhotoKey();
						commentsPageRequest.CommentedOnKey.Key = key;
						commentsPageRequest.OneBasedOnPage = 0;

						mattel_pluck.queue(commentsPageRequest);
					}
					else {
						photoGalleryRegion.find('.pluck-photo-selection-gallery').append('<li class="pluck-photo-gallery-item" id="' + key + '" user="' + user + '"><img src="' + mattel_pluck.getImageUrl(photo.Image.Full, preset) + '" /></li>');
					}
				})

				if (photoContentPage < photoContentTotalPages) {
					photoGalleryRegion.find('.pluck-photo-pager-next').show();
					if (photoGalleryRegion.find('.pluck-photo-selection-gallery').hasClass('pluck-photo-pageable')) {
						photoGalleryRegion.find('.pluck-photo-selection-gallery').append('<li class="pluck-photo-gallery-next">next</li>');
					}
				}
				else {
					photoGalleryRegion.find('.pluck-photo-pager-next').hide();
				}

				photoGalleryRegion.find('.pluck-photo-selection-gallery li').click(function () {
					var elem = $(this);

					if (elem.hasClass('pluck-photo-gallery-prev')) {
						photoContentPage = photoContentPage - 1;
						_getGalleryPhotos();
					}
					else if (elem.hasClass('pluck-photo-gallery-next')) {
						photoContentPage = photoContentPage + 1;
						_getGalleryPhotos();
					}
					else if (elem.hasClass('pluck-photo-gallery-item')) {
						var key = elem.attr('id');
						var user = elem.attr('user');
						var userCustomKey = pluckContentPrefix + 'user_' + pluckUserPrefix + user;

						if (photoGalleryRegion.find('.pluck-photo-selection-gallery').hasClass('pluck-photo-use-overlay')) {
							photoContentPhotoKey = key;
							_getOverlay(userCustomKey);
						}
						else if (key != photoContentPhotoKey || userCustomKey != customKey) {
							window.location.assign(baseUrl + '/user/' + user + '/photos/' + key + '#user-photo');
						}
					}
				});

				if (photoGalleryRegion.find('.pluck-photo-selection-gallery').hasClass('pluck-photo-num-comments')) {
					mattel_pluck.setResultsCallback(_loadGalleryCommentCounts);
					mattel_pluck.send();
				}
			}
			else {
				photoAlternativeRegion.show();
			}
		}
	}

	function _loadOverlay(responses) {
		if (responses[0].ResponseStatus.StatusCode != PluckSDK.ResponseStatusCode.OK && responses[1].ResponseStatus.StatusCode != PluckSDK.ResponseStatusCode.OK) {
			photoAlternativeRegion.show();
		}
		else {
			var photo = responses[0].Photo;
			var totalPhotos = responses[1].TotalItems;

			if (photo.Tags.indexOf(customKey) != -1) {
				var user = photo.Owner.UserKey.Key;
				user = user.substr(pluckUserPrefix.length);
				var products = _getValuesFromTagsWithPrefix(photo.Tags, pluckContentPrefix + 'product_');

				$.ajax({
					'url':      '/ajax/bc-pluck/photo',
					'type':     'POST',
					'data': {
						'op':       'overlay',
						'user':     user,
						'products': products.toString()
					},
					'dataType': 'text',
					'success':  function (data) {
						data = data.replace('!url', mattel_pluck.getImageUrl(photo.Image.Full, 'pluck_photo_overlay'));
						data = data.replace('!title', photo.Title);
						if (totalPhotos == 1) {
							data = data.replace('!num_photos', Drupal.t('1 photo'));
						}
						else {
							data = data.replace('!num_photos', Drupal.t('!num photos', {
									'!num': totalPhotos
								}
							));
						}

						_createOverlay(data);
					}
				});
			}
			else {
				photoAlternativeRegion.show();
			}
		}
	}

	function _loadGalleryCommentCounts(responses) {
		var lis = photoGalleryRegion.find('.pluck-photo-selection-gallery li');

		$.each(responses, function (i, response) {
			if (response.ResponseStatus.StatusCode != PluckSDK.ResponseStatusCode.OK) {
			}
			else {
				var li = lis[i];
				$('.pluck-photo-comment-count', li).text(response.TotalItems);
			}
		});
	}

	function _populateSelectionGallery() {
		var start = (photoContentPage == 1) ? 0 : 1 + (photoContentPage - 1) * (photoContentPerPage - 2);
		var end = (photoContentPage == 1) ? photoContentPerPage - 1 : start + (photoContentPerPage - 2);

		photoContentRegion.find('.pluck-photo-selection-gallery').html('');

		if (photoContentPage > 1) {
			photoContentRegion.find('.pluck-photo-selection-gallery').append('<li class="pluck-photo-gallery-prev"><span>' + Drupal.t('See more photos') + '</span></li>');
		}

		for (var i = start; i < end && typeof(photoList[i]) != 'undefined'; i++) {
			var key = photoList[i].PhotoKey.Key;
			var user = photoList[i].Owner.UserKey.Key;
			user = user.substr(pluckUserPrefix.length);
			var preset;
			if (photoContentRegion.find('.pluck-photo-selection-gallery').attr('preset')) {
				preset = photoContentRegion.find('.pluck-photo-selection-gallery').attr('preset');
			}

			if (key == photoContentPhotoKey) {
				photoContentRegion.find('.pluck-photo-selection-gallery').append('<li class="pluck-photo-gallery-selected-item"><img src="' + mattel_pluck.getImageUrl(photoList[i].Image.Full, preset) + '" /></li>');
			}
			else {
				photoContentRegion.find('.pluck-photo-selection-gallery').append('<li class="pluck-photo-gallery-item" id="' + key + '" user="' + user + '"><img src="' + mattel_pluck.getImageUrl(photoList[i].Image.Full, preset) + '" /></li>');
			}
		}

		if (end < (photoList.length)) {
			photoContentRegion.find('.pluck-photo-selection-gallery').append('<li class="pluck-photo-gallery-next"><span>' + Drupal.t('See more photos') + '</span></li>');
		}

		photoContentRegion.find('.pluck-photo-selection-gallery li').click(function () {
			var elem = $(this);

			if (elem.hasClass('pluck-photo-gallery-prev')) {
				photoContentPage = photoContentPage - 1;
				_populateSelectionGallery();
			}
			else if (elem.hasClass('pluck-photo-gallery-next')) {
				photoContentPage = photoContentPage + 1;
				_populateSelectionGallery();
			}
			else if (elem.hasClass('pluck-photo-gallery-item')) {
				var key = elem.attr('id');
				var user = elem.attr('user');
				var userCustomKey = pluckContentPrefix + 'user_' + pluckUserPrefix + user;

				if (key != photoContentPhotoKey || userCustomKey != customKey) {
					window.location.assign(baseUrl + '/user/' + user + '/photos/' + key + '#user-photo');
				}
			}
		});
	}

	function _getPhotoInPhotoRegion(products) {
		if (products.length) {
			$.ajax({
				'url':      '/ajax/bc-pluck/photo',
				'type':     'POST',
				'data': {
					'op':       'in-photo',
					'products': products.toString()
				},
				'dataType': 'json',
				'success':  function (data) {
					photoContentRegion.find('.pluck-photo-in-photo').html('');

					$.each(data, function (i, v) {
						photoContentRegion.find('.pluck-photo-in-photo').append('<li><span>' + v + '</span></li>');
					});
				}
			});
		}
	}

	function _getPhotoInfoRegion(user, creationDate) {
		$.ajax({
			'url':      '/ajax/bc-pluck/photo',
			'type':     'POST',
			'data': {
				'op':      'info',
				'user':    user,
				'created': creationDate
			},
			'dataType': 'html',
			'success':  function (data) {
				photoContentRegion.find('.pluck-photo-info').html(data);
				_getGalleryInfo(_getPhotoInfoRegionExtras, pluckContentPrefix + 'user_' + pluckUserPrefix + user);
			}
		});
	}

	function _getPhotoInfoRegionExtras(responses) {
		if (responses[0].ResponseStatus.StatusCode != PluckSDK.ResponseStatusCode.OK) {
		}
		else {
			var tmpPhotoContentTotalItems = photoContentTotalItems
			photoContentTotalItems = responses[0].TotalItems;
			_getPhotoPageInfo(photoContentRegion.find('.pluck-photo-info'));
			photoContentTotalItems = tmpPhotoContentTotalItems;
		}
	}

	function _getSinglePhotoPagers() {
		var user = photoList[0].Owner.UserKey.Key;
		user = user.substr(pluckUserPrefix.length);

		$.each(photoList, function (i, photo) {
			i = parseInt(i);
			if (photo.PhotoKey.Key == photoContentPhotoKey) {
				if (i != 0) {
					photoContentRegion.find('.pluck-photo').prepend('<span class="pluck-photo-prev">prev</span>');
				}
				if ((i + 1) < photoList.length) {
					photoContentRegion.find('.pluck-photo').append('<span class="pluck-photo-next">next</span>');
				}

				photoContentRegion.find('.pluck-photo span').click(function () {
					elem = $(this);
					if (elem.hasClass('pluck-photo-prev')) {
						window.location.assign(baseUrl + '/user/' + user + '/photos/' + photoList[i - 1].PhotoKey.Key + '#user-photo');
					}
					else if (elem.hasClass('pluck-photo-next')) {
						window.location.assign(baseUrl + '/user/' + user + '/photos/' + photoList[i + 1].PhotoKey.Key + '#user-photo');
					}
				});
				return;
			}
		});
	}

	function _getPhotoPageInfo(elem) {
		var start = (photoContentPerPage * (photoContentPage - 1)) + 1;
		var end = Math.min(photoContentPerPage * photoContentPage, photoContentTotalItems);

		elem.find('.pluck-photo-page-info-start').text(start);
		elem.find('.pluck-photo-page-info-end').text(end);
		if (elem.find('.pluck-photo-page-info-total').hasClass('pluck-photo-page-info-text')) {
			if (photoContentTotalItems == 1) {
				elem.find('.pluck-photo-page-info-total').text(Drupal.t('1 photo'));
			}
			else {
				elem.find('.pluck-photo-page-info-total').text(Drupal.t('!count photos', {'!count': photoContentTotalItems}));
			}
		}
		else {
			elem.find('.pluck-photo-page-info-total').text(photoContentTotalItems);
		}
	}

	function _getValuesFromTagsWithPrefix(tagString, prefix) {
		var tags = tagString.split(' ');
		var values = [];

		$.each(tags, function (i, tag) {
			if (tag.indexOf(prefix) != -1) {
				var value = tag.substr(prefix.length);
				values.push(value);
			}
		});

		return values;
	}

	function _createOverlay(data) {
		var wrapoverlay = $('<div id="photo_overlay"><a id="close-button" class="close"></a><div class="contentWrap"></div></div>').appendTo( $('body') );

		overlay = wrapoverlay.overlay({
			'fixed':false,
			'load':true,
			'mask': {
				'color':       '#000',
				'loadSpeed':    0,
				'closeSpeed':   0,
				'startOpacity': 0.4,
				'opacity':      0.6
			},
			'onBeforeLoad': function() {
				var wrap = this.getOverlay().find(".contentWrap").html(data);
			},
			'onClose': function() {
				wrapoverlay.remove();
			}
		});
	}

	if (photoContentRegion.length) {
		if (photoContentRegion.attr('id')) {
			photoContentPhotoKey = photoContentRegion.attr('id');
		}

		_getSinglePhoto();
		if (photoContentRegion.find('.pluck-photo-selection-gallery').length) {
			photoContentPerPage = (photoContentRegion.find('.pluck-photo-selection-gallery').attr('perpage')) ? photoContentRegion.find('.pluck-photo-selection-gallery').attr('perpage') : 12;

			_getGalleryInfo(_loadSelectionGalleryFromInfo);
		}
	}
	else if (photoGalleryRegion.length) {
		photoContentPage = 1;
		photoContentPerPage = (photoGalleryRegion.find('.pluck-photo-selection-gallery').attr('perpage')) ? photoGalleryRegion.find('.pluck-photo-selection-gallery').attr('perpage') : 12;

		_bindGalleryRegion();
		_getGalleryPhotos();
	}
	else {
		photoAlternativeRegion.show();
	}
}

Drupal.behaviors.pluck_photo = function(context) {
	if (typeof(mattel_pluck) != 'undefined') {
		$('.user-photo', context).each(function () {
			var user_photos = new PluckPhoto($(this));
		});
		$('.collection-photo', context).each(function () {
			var user_photos = new PluckPhoto($(this));
		});
		$('.doll-photo', context).each(function () {
			var user_photos = new PluckPhoto($(this));
		});
		$('.shoot-photo', context).each(function () {
			var user_photos = new PluckPhoto($(this));
		});
		$('.all-photo', context).each(function () {
			var user_photos = new PluckPhoto($(this));
		});
	}
};
;
/*
 * jQuery Form Plugin
 * version: 2.25 (08-APR-2009)
 * @requires jQuery v1.2.2 or later
 * @note This has been modified for ajax.module
 * 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
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};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}(';(5($){$.B.1s=5(u){2(!4.G){R(\'1b: 2M 9 2N - 2O 2P 1t\');6 4}2(S u==\'5\')u={T:u};3 v=4.14(\'1c\')||1d.2Q.2R;v=(v.2S(/^([^#]+)/)||[])[1];v=v||\'\';u=$.1n({1e:v,H:4.14(\'1u\')||\'1Q\'},u||{});3 w={};4.L(\'C-1R-1S\',[4,u,w]);2(w.1T){R(\'1b: 9 1U 1o C-1R-1S L\');6 4}2(u.1v&&u.1v(4,u)===I){R(\'1b: 9 1f 1o 1v 1V\');6 4}3 a=4.1w(u.2T);2(u.J){u.O=u.J;K(3 n 1x u.J){2(u.J[n]2U 15){K(3 k 1x u.J[n])a.D({7:n,8:u.J[n][k]})}E a.D({7:n,8:u.J[n]})}}2(u.1y&&u.1y(a,4,u)===I){R(\'1b: 9 1f 1o 1y 1V\');6 4}4.L(\'C-9-1W\',[a,4,u,w]);2(w.1T){R(\'1b: 9 1U 1o C-9-1W L\');6 4}3 q=$.1z(a);2(u.H.2V()==\'1Q\'){u.1e+=(u.1e.2W(\'?\')>=0?\'&\':\'?\')+q;u.J=F}E u.J=q;3 x=4,V=[];2(u.2X)V.D(5(){x.1X()});2(u.2Y)V.D(5(){x.1Y()});2(!u.16&&u.17){3 y=u.T||5(){};V.D(5(a){$(u.17).2Z(a).P(y,1Z)})}E 2(u.T)V.D(u.T);u.T=5(a,b){K(3 i=0,M=V.G;i<M;i++)V[i].30(u,[a,b,x])};3 z=$(\'W:31\',4).18();3 A=I;K(3 j=0;j<z.G;j++)2(z[j])A=Q;2(u.20||A){2(u.21)$.32(u.21,1A);E 1A()}E $.33(u);4.L(\'C-9-34\',[4,u]);6 4;5 1A(){3 h=x[0];2($(\':W[7=9]\',h).G){35(\'36: 37 22 38 39 3a 3b "9".\');6}3 i=$.1n({},$.23,u);3 s=$.1n(Q,{},$.1n(Q,{},$.23),i);3 j=\'3c\'+(1B 3d().3e());3 k=$(\'<20 3f="\'+j+\'" 7="\'+j+\'" 24="25:26" />\');3 l=k[0];k.3g({3h:\'3i\',27:\'-28\',29:\'-28\'});3 m={1f:0,19:F,1g:F,3j:0,3k:\'n/a\',3l:5(){},2a:5(){},3m:5(){},3n:5(){4.1f=1;k.14(\'24\',\'25:26\')}};3 g=i.2b;2(g&&!$.1C++)$.1h.L("3o");2(g)$.1h.L("3p",[m,i]);2(s.2c&&s.2c(m,s)===I){s.2b&&$.1C--;6}2(m.1f)6;3 o=0;3 p=0;3 q=h.U;2(q){3 n=q.7;2(n&&!q.1i){u.O=u.O||{};u.O[n]=q.8;2(q.H=="X"){u.O[7+\'.x\']=h.Y;u.O[7+\'.y\']=h.Z}}}1j(5(){3 t=x.14(\'17\'),a=x.14(\'1c\');h.1k(\'17\',j);2(h.2d(\'1u\')!=\'2e\')h.1k(\'1u\',\'2e\');2(h.2d(\'1c\')!=i.1e)h.1k(\'1c\',i.1e);2(!u.3q){x.14({3r:\'2f/C-J\',3s:\'2f/C-J\'})}2(i.1D)1j(5(){p=Q;11()},i.1D);3 b=[];2g{2(u.O)K(3 n 1x u.O)b.D($(\'<W H="3t" 7="\'+n+\'" 8="\'+u.O[n]+\'" />\').2h(h)[0]);k.2h(\'1l\');l.2i?l.2i(\'2j\',11):l.3u(\'2k\',11,I);h.9()}3v{h.1k(\'1c\',a);t?h.1k(\'17\',t):x.3w(\'17\');$(b).2l()}},10);3 r=0;5 11(){2(o++)6;l.2m?l.2m(\'2j\',11):l.3x(\'2k\',11,I);3 c=Q;2g{2(p)3y\'1D\';3 d,N;N=l.2n?l.2n.2o:l.2p?l.2p:l.2o;2((N.1l==F||N.1l.2q==\'\')&&!r){r=1;o--;1j(11,2r);6}m.19=N.1l?N.1l.2q:F;m.1g=N.2s?N.2s:N;m.2a=5(a){3 b={\'3z-H\':i.16};6 b[a]};2(i.16==\'3A\'||i.16==\'3B\'){3 f=N.1E(\'1F\')[0];m.19=f?f.8:m.19}E 2(i.16==\'2t\'&&!m.1g&&m.19!=F){m.1g=2u(m.19)}d=$.3C(m,i.16)}3D(e){c=I;$.3E(i,m,\'2v\',e)}2(c){i.T(d,\'T\');2(g)$.1h.L("3F",[m,i])}2(g)$.1h.L("3G",[m,i]);2(g&&!--$.1C)$.1h.L("3H");2(i.2w)i.2w(m,c?\'T\':\'2v\');1j(5(){k.2l();m.1g=F},2r)};5 2u(s,a){2(1d.2x){a=1B 2x(\'3I.3J\');a.3K=\'I\';a.3L(s)}E a=(1B 3M()).3N(s,\'1G/2t\');6(a&&a.2y&&a.2y.1p!=\'3O\')?a:F}}};$.B.3P=5(c){6 4.2z().2A(\'9.C-1q\',5(){$(4).1s(c);6 I}).P(5(){$(":9,W:X",4).2A(\'2B.C-1q\',5(e){3 a=4.C;a.U=4;2(4.H==\'X\'){2(e.2C!=12){a.Y=e.2C;a.Z=e.3Q}E 2(S $.B.2D==\'5\'){3 b=$(4).2D();a.Y=e.2E-b.29;a.Z=e.2F-b.27}E{a.Y=e.2E-4.3R;a.Z=e.2F-4.3S}}1j(5(){a.U=a.Y=a.Z=F},10)})})};$.B.2z=5(){4.2G(\'9.C-1q\');6 4.P(5(){$(":9,W:X",4).2G(\'2B.C-1q\')})};$.B.1w=5(b){3 a=[];2(4.G==0)6 a;3 c=4[0];3 d=b?c.1E(\'*\'):c.22;2(!d)6 a;K(3 i=0,M=d.G;i<M;i++){3 e=d[i];3 n=e.7;2(!n)1H;2(b&&c.U&&e.H=="X"){2(!e.1i&&c.U==e)a.D({7:n+\'.x\',8:c.Y},{7:n+\'.y\',8:c.Z});1H}3 v=$.18(e,Q);2(v&&v.1r==15){K(3 j=0,2H=v.G;j<2H;j++)a.D({7:n,8:v[j]})}E 2(v!==F&&S v!=\'12\')a.D({7:n,8:v})}2(!b&&c.U){3 f=c.1E("W");K(3 i=0,M=f.G;i<M;i++){3 g=f[i];3 n=g.7;2(n&&!g.1i&&g.H=="X"&&c.U==g)a.D({7:n+\'.x\',8:c.Y},{7:n+\'.y\',8:c.Z})}}6 a};$.B.3T=5(a){6 $.1z(4.1w(a))};$.B.3U=5(b){3 a=[];4.P(5(){3 n=4.7;2(!n)6;3 v=$.18(4,b);2(v&&v.1r==15){K(3 i=0,M=v.G;i<M;i++)a.D({7:n,8:v[i]})}E 2(v!==F&&S v!=\'12\')a.D({7:4.7,8:v})});6 $.1z(a)};$.B.18=5(a){K(3 b=[],i=0,M=4.G;i<M;i++){3 c=4[i];3 v=$.18(c,a);2(v===F||S v==\'12\'||(v.1r==15&&!v.G))1H;v.1r==15?$.3V(b,v):b.D(v)}6 b};$.18=5(b,c){3 n=b.7,t=b.H,1a=b.1p.1I();2(S c==\'12\')c=Q;2(c&&(!n||b.1i||t==\'1m\'||t==\'3W\'||(t==\'1J\'||t==\'1K\')&&!b.1L||(t==\'9\'||t==\'X\')&&b.C&&b.C.U!=b||1a==\'13\'&&b.1M==-1))6 F;2(1a==\'13\'){3 d=b.1M;2(d<0)6 F;3 a=[],1N=b.3X;3 e=(t==\'13-2I\');3 f=(e?d+1:1N.G);K(3 i=(e?d:0);i<f;i++){3 g=1N[i];2(g.1t){3 v=g.8;2(!v)v=(g.1O&&g.1O[\'8\']&&!(g.1O[\'8\'].3Y))?g.1G:g.8;2(e)6 v;a.D(v)}}6 a}6 b.8};$.B.1Y=5(){6 4.P(5(){$(\'W,13,1F\',4).2J()})};$.B.2J=$.B.3Z=5(){6 4.P(5(){3 t=4.H,1a=4.1p.1I();2(t==\'1G\'||t==\'40\'||1a==\'1F\')4.8=\'\';E 2(t==\'1J\'||t==\'1K\')4.1L=I;E 2(1a==\'13\')4.1M=-1})};$.B.1X=5(){6 4.P(5(){2(S 4.1m==\'5\'||(S 4.1m==\'41\'&&!4.1m.42))4.1m()})};$.B.43=5(b){2(b==12)b=Q;6 4.P(5(){4.1i=!b})};$.B.2K=5(b){2(b==12)b=Q;6 4.P(5(){3 t=4.H;2(t==\'1J\'||t==\'1K\')4.1L=b;E 2(4.1p.1I()==\'2L\'){3 a=$(4).44(\'13\');2(b&&a[0]&&a[0].H==\'13-2I\'){a.45(\'2L\').2K(I)}4.1t=b}})};5 R(){2($.B.1s.46&&1d.1P&&1d.1P.R)1d.1P.R(\'[47.C] \'+15.48.49.4a(1Z,\'\'))}})(4b);',62,260,'||if|var|this|function|return|name|value|submit||||||||||||||||||||||||||||fn|form|push|else|null|length|type|false|data|for|trigger|max|doc|extraData|each|true|log|typeof|success|clk|callbacks|input|image|clk_x|clk_y||cb|undefined|select|attr|Array|dataType|target|a_fieldValue|responseText|tag|ajaxSubmit|action|window|url|aborted|responseXML|event|disabled|setTimeout|setAttribute|body|reset|extend|via|tagName|plugin|constructor|a_ajaxSubmit|selected|method|beforeSerialize|a_formToArray|in|beforeSubmit|param|fileUpload|new|active|timeout|getElementsByTagName|textarea|text|continue|toLowerCase|checkbox|radio|checked|selectedIndex|ops|attributes|console|GET|pre|serialize|veto|vetoed|callback|validate|a_resetForm|a_clearForm|arguments|iframe|closeKeepAlive|elements|ajaxSettings|src|about|blank|top|1000px|left|getResponseHeader|global|beforeSend|getAttribute|POST|multipart|try|appendTo|attachEvent|onload|load|remove|detachEvent|contentWindow|document|contentDocument|innerHTML|100|XMLDocument|xml|toXml|error|complete|ActiveXObject|documentElement|a_ajaxFormUnbind|bind|click|offsetX|offset|pageX|pageY|unbind|jmax|one|a_clearFields|a_selected|option|skipping|process|no|element|location|href|match|semantic|instanceof|toUpperCase|indexOf|resetForm|clearForm|html|apply|file|get|ajax|notify|alert|Error|Form|must|not|be|named|jqFormIO|Date|getTime|id|css|position|absolute|status|statusText|getAllResponseHeaders|setRequestHeader|abort|ajaxStart|ajaxSend|skipEncodingOverride|encoding|enctype|hidden|addEventListener|finally|removeAttr|removeEventListener|throw|content|json|script|httpData|catch|handleError|ajaxSuccess|ajaxComplete|ajaxStop|Microsoft|XMLDOM|async|loadXML|DOMParser|parseFromString|parsererror|a_ajaxForm|offsetY|offsetLeft|offsetTop|a_formSerialize|a_fieldSerialize|merge|button|options|specified|a_clearInputs|password|object|nodeType|a_enable|parent|find|debug|jquery|prototype|join|call|jQuery'.split('|'),0,{}));
/**
 * Automatic ajax validation
 *
 * @see http://drupal.org/project/ajax
 * @see irc://freenode.net/#drupy
 * @depends Drupal 6
 * @author brendoncrawford
 * @note This file uses a 79 character width limit.
 * 
 *
 */

Drupal.Ajax = new Object;

Drupal.Ajax.plugins = {};

Drupal.Ajax.firstRun = false;

/**
 * Init function.
 * This is being executed by Drupal behaviours.
 * See bottom of script.
 * 
 * @param {HTMLElement} context
 * @return {Bool}
 */
Drupal.Ajax.init = function(context) {
  var f, s;
  if (f = $('.ajax-form', context)) {
    if (!Drupal.Ajax.firstRun) {
      Drupal.Ajax.invoke('init');
      Drupal.Ajax.firstRun = true;
    }
    s = $('input[type="submit"]', f);
    s.click(function(){
      this.form.ajax_activator = $(this);
      return true;
    });
    f.each(function(){
      this.ajax_activator = null;
      $(this).submit(function(){
        if (this.ajax_activator === null) {
          this.ajax_activator = $('#edit-submit', this);
        }
        if (this.ajax_activator.hasClass('ajax-trigger')) {
          Drupal.Ajax.go($(this), this.ajax_activator);
          return false;
        }
        else {
          return true;
        }
      });
      return true;
    });
  }
  return true;
};

/**
 * Invokes plugins
 * 
 * @param {Object} formObj
 * @param {Object} submitter
 */
Drupal.Ajax.invoke = function(hook, args) {
  var plugin, r, ret;
  ret = true;
  for (plugin in Drupal.Ajax.plugins) {
    r = Drupal.Ajax.plugins[plugin](hook, args);
    if (r === false) {
      ret = false;
    }
  }
  return ret;
};

/**
 * Handles submission
 * 
 * @param {Object} submitter_
 * @return {Bool}
 */
Drupal.Ajax.go = function(formObj, submitter) {
  var submitterVal, submitterName, extraData;
  Drupal.Ajax.invoke('submit', {submitter:submitter});
  submitterVal = submitter.val();
  submitterName = submitter.attr('name');
  submitter.val(Drupal.t('Loading...'));
  extraData = {};
  extraData[submitterName] = submitterVal;
  extraData['drupal_ajax'] = '1';
  formObj.a_ajaxSubmit({
    extraData : extraData,
    beforeSubmit : function(data) {
      data[data.length] = {
        name : submitterName,
        value : submitterVal
      };
      data[data.length] = {
        name : 'drupal_ajax',
        value : '1'
      };
      return true;
    },
    dataType : 'json',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      //window.alert(Drupal.t('ajax.module: An unknown error has occurred.'));
      if (window.console) {
        console.log('error', arguments);
      }
      return true;
    },
    success: function(data){
      submitter.val(submitterVal);
      Drupal.Ajax.response(submitter, formObj, data);
      return true;
    }
  });
  return false;
};

/**
 * Handles messaging
 * 
 * @param {Object} formObj
 * @param {Object} submitter
 * @param {Object} data
 * @param {Object} options
 * @return {Bool}
 */
Drupal.Ajax.message = function(formObj, submitter, data, options) {
  var args;
  data.local = {
    submitter : submitter,
    form : formObj
  };
  if (Drupal.Ajax.invoke('message', data)) {
    Drupal.Ajax.writeMessage(data.local.form, data.local.submitter, options);
    Drupal.Ajax.invoke('afterMessage', data);
  }
  return true;
};

/**
 * Writes message
 * 
 * @param {Object} formObj
 * @param {Object} submitter
 * @param {Object} options
 * @return {Bool}
 */
Drupal.Ajax.writeMessage = function(formObj, submitter, options) {
  var i, _i, thisItem, log, errBox, h, data;
  if (options.action === 'notify') {
    // Cleanups
    $('.messages, .ajax-preview', formObj).remove();
    $('input, textarea').removeClass('error status warning required');
    // Preview
    if (options.type === 'preview') {
      log = $('<div>').addClass('ajax-preview');
      log.html(options.messages);
      formObj.prepend(log);
    }
    // Status, Error, Message
    else {
      log = $('<ul>');
      errBox = $(".messages." + options.type, formObj[0])
      for (i = 0, _i = options.messages.length; i < _i; i++) {
        thisItem = $('#' + options.messages[i].id, formObj[0])
        thisItem.addClass(options.type);
        if (options.messages[i].required) {
          thisItem.addClass('required');
        }
        log.append('<li>' + options.messages[i].value + '</li>');
      }
      if (errBox.length === 0) {
        errBox = $("<div class='messages " + options.type + "'>");
        formObj.prepend(errBox);
      }
      errBox.html(log);
    }
  }
  else if (options.action === 'clear') {
    $('.messages, .ajax-preview', formObj).remove();
  }
  return true;
};

/**
 * Updates message containers
 * 
 * @param {Object} updaters
 * @return {Bool}
 */
Drupal.Ajax.updater = function(updaters) {
  var i, _i, elm;
  for (i = 0, _i = updaters.length; i < _i; i++) {
    elm = $(updaters[i].selector);
    // HTML:IN
    if (updaters[i].type === 'html_in') {
      elm.html(updaters[i].value);
    }
    // HTML:OUT
    else if (updaters[i].type === 'html_out') {
      elm.replaceWith(updaters[i].value);
    }
    // FIELD
    else if (updaters[i].type === 'field') {
      elm.val(updaters[i].value);
    }
    // REMOVE
    else if(updaters[i].type === 'remove') {
      elm.remove();
    }
  }
  return true;
};

/**
 * Handles data response
 * 
 * @param {Object} submitter
 * @param {Object} formObj
 * @param {Object} data
 * @return {Bool}
 */
Drupal.Ajax.response = function(submitter, formObj, data){
  var newSubmitter;
  data.local = {
    submitter : submitter,
    form : formObj
  };
  /**
   * Failure
   */
  if (data.status === false) {
    Drupal.Ajax.updater(data.updaters);
    Drupal.Ajax.message(formObj, submitter, data, {
      action : 'notify',
      messages : data.messages_error,
      type : 'error'
    });
  }
  /**
   * Success
   */
  else {
    // Display preview
    if (data.preview !== null) {
      Drupal.Ajax.updater(data.updaters);
      Drupal.Ajax.message(formObj, submitter, data, {
        action : 'notify',
        messages : decodeURIComponent(data.preview),
        type : 'preview'
      });
    }
    // If no redirect, then simply show messages
    else if (data.redirect === null) {
      if (data.messages_status.length > 0) {
        Drupal.Ajax.message(formObj, submitter, data, {
          action : 'notify',
          messages : data.messages_status,
          type : 'status'
        });
      }
      if (data.messages_warning.length > 0) {
        Drupal.Ajax.message(formObj, submitter, data, {
          action : 'notify',
          messages : data.messages_warning,
          type : 'warning'
        });
      }
      if (data.messages_status.length === 0 &&
          data.messages_warning.length === 0) {
        Drupal.Ajax.message(formObj, submitter, data, {action:'clear'});
      }
    }
    // Redirect
    else {
      if (Drupal.Ajax.invoke('redirect', data)) {
        Drupal.Ajax.redirect( data.redirect );
      }
      else {
        Drupal.Ajax.updater(data.updaters);
        if (data.messages_status.length === 0 &&
            data.messages_warning.length === 0) {
          Drupal.Ajax.message(formObj, submitter, data, {action:'clear'});
        }
        else {
          Drupal.Ajax.message(formObj, submitter, data, {
            action : 'notify',
            messages : data.messages_status,
            type : 'status'
          });
        }
      }
    }
  }
  return true;
};


/**
 * Redirects to appropriate page
 * 
 * @todo
 *   Some of this functionality should possibly hapen on
 *   the server instead of client.
 * @param {String} url
 */
Drupal.Ajax.redirect = function(url) {
  window.location.href = url;
};

Drupal.behaviors.Ajax = Drupal.Ajax.init;


;

