
(function(){
  var uid = window.location.hash.match(/#redirect-(.*)/);
  if(uid && uid[1]){
    var path = window.location.pathname;
    path = path.replace(/(.*\/)(\d+)(\/?)$/, "$1" + uid[1] + "$3");
    window.location.href = path+window.location.search;
  }
})();

/*
 * jQuery JavaScript Library v1.3.2
 * http://jquery.com/
 *
 * Copyright (c) 2009 John Resig
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
 * Revision: 6246
 */
(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});
/*
 * Sizzle CSS Selector Engine - v0.9.3
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML='   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})();
jQuery.ui||(function(c){var i=c.fn.remove,d=c.browser.mozilla&&(parseFloat(c.browser.version)<1.9);c.ui={version:"1.7.1",plugin:{add:function(k,l,n){var m=c.ui[k].prototype;for(var j in n){m.plugins[j]=m.plugins[j]||[];m.plugins[j].push([l,n[j]])}},call:function(j,l,k){var n=j.plugins[l];if(!n||!j.element[0].parentNode){return}for(var m=0;m<n.length;m++){if(j.options[n[m][0]]){n[m][1].apply(j.element,k)}}}},contains:function(k,j){return document.compareDocumentPosition?k.compareDocumentPosition(j)&16:k!==j&&k.contains(j)},hasScroll:function(m,k){if(c(m).css("overflow")=="hidden"){return false}var j=(k&&k=="left")?"scrollLeft":"scrollTop",l=false;if(m[j]>0){return true}m[j]=1;l=(m[j]>0);m[j]=0;return l},isOverAxis:function(k,j,l){return(k>j)&&(k<(j+l))},isOver:function(o,k,n,m,j,l){return c.ui.isOverAxis(o,n,j)&&c.ui.isOverAxis(k,m,l)},keyCode:{BACKSPACE:8,CAPS_LOCK:20,COMMA:188,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38}};if(d){var f=c.attr,e=c.fn.removeAttr,h="http://www.w3.org/2005/07/aaa",a=/^aria-/,b=/^wairole:/;c.attr=function(k,j,l){var m=l!==undefined;return(j=="role"?(m?f.call(this,k,j,"wairole:"+l):(f.apply(this,arguments)||"").replace(b,"")):(a.test(j)?(m?k.setAttributeNS(h,j.replace(a,"aaa:"),l):f.call(this,k,j.replace(a,"aaa:"))):f.apply(this,arguments)))};c.fn.removeAttr=function(j){return(a.test(j)?this.each(function(){this.removeAttributeNS(h,j.replace(a,""))}):e.call(this,j))}}c.fn.extend({remove:function(){c("*",this).add(this).each(function(){c(this).triggerHandler("remove")});return i.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","").unbind("selectstart.ui")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect","none").bind("selectstart.ui",function(){return false})},scrollParent:function(){var j;if((c.browser.msie&&(/(static|relative)/).test(this.css("position")))||(/absolute/).test(this.css("position"))){j=this.parents().filter(function(){return(/(relative|absolute|fixed)/).test(c.curCSS(this,"position",1))&&(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}else{j=this.parents().filter(function(){return(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}return(/fixed/).test(this.css("position"))||!j.length?c(document):j}});c.extend(c.expr[":"],{data:function(l,k,j){return !!c.data(l,j[3])},focusable:function(k){var l=k.nodeName.toLowerCase(),j=c.attr(k,"tabindex");return(/input|select|textarea|button|object/.test(l)?!k.disabled:"a"==l||"area"==l?k.href||!isNaN(j):!isNaN(j))&&!c(k)["area"==l?"parents":"closest"](":hidden").length},tabbable:function(k){var j=c.attr(k,"tabindex");return(isNaN(j)||j>=0)&&c(k).is(":focusable")}});function g(m,n,o,l){function k(q){var p=c[m][n][q]||[];return(typeof p=="string"?p.split(/,?\s+/):p)}var j=k("getter");if(l.length==1&&typeof l[0]=="string"){j=j.concat(k("getterSetter"))}return(c.inArray(o,j)!=-1)}c.widget=function(k,j){var l=k.split(".")[0];k=k.split(".")[1];c.fn[k]=function(p){var n=(typeof p=="string"),o=Array.prototype.slice.call(arguments,1);if(n&&p.substring(0,1)=="_"){return this}if(n&&g(l,k,p,o)){var m=c.data(this[0],k);return(m?m[p].apply(m,o):undefined)}return this.each(function(){var q=c.data(this,k);(!q&&!n&&c.data(this,k,new c[l][k](this,p))._init());(q&&n&&c.isFunction(q[p])&&q[p].apply(q,o))})};c[l]=c[l]||{};c[l][k]=function(o,n){var m=this;this.namespace=l;this.widgetName=k;this.widgetEventPrefix=c[l][k].eventPrefix||k;this.widgetBaseClass=l+"-"+k;this.options=c.extend({},c.widget.defaults,c[l][k].defaults,c.metadata&&c.metadata.get(o)[k],n);this.element=c(o).bind("setData."+k,function(q,p,r){if(q.target==o){return m._setData(p,r)}}).bind("getData."+k,function(q,p){if(q.target==o){return m._getData(p)}}).bind("remove",function(){return m.destroy()})};c[l][k].prototype=c.extend({},c.widget.prototype,j);c[l][k].getterSetter="option"};c.widget.prototype={_init:function(){},destroy:function(){this.element.removeData(this.widgetName).removeClass(this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").removeAttr("aria-disabled")},option:function(l,m){var k=l,j=this;if(typeof l=="string"){if(m===undefined){return this._getData(l)}k={};k[l]=m}c.each(k,function(n,o){j._setData(n,o)})},_getData:function(j){return this.options[j]},_setData:function(j,k){this.options[j]=k;if(j=="disabled"){this.element[k?"addClass":"removeClass"](this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").attr("aria-disabled",k)}},enable:function(){this._setData("disabled",false)},disable:function(){this._setData("disabled",true)},_trigger:function(l,m,n){var p=this.options[l],j=(l==this.widgetEventPrefix?l:this.widgetEventPrefix+l);m=c.Event(m);m.type=j;if(m.originalEvent){for(var k=c.event.props.length,o;k;){o=c.event.props[--k];m[o]=m.originalEvent[o]}}this.element.trigger(m,n);return !(c.isFunction(p)&&p.call(this.element[0],m,n)===false||m.isDefaultPrevented())}};c.widget.defaults={disabled:false};c.ui.mouse={_mouseInit:function(){var j=this;this.element.bind("mousedown."+this.widgetName,function(k){return j._mouseDown(k)}).bind("click."+this.widgetName,function(k){if(j._preventClickEvent){j._preventClickEvent=false;k.stopImmediatePropagation();return false}});if(c.browser.msie){this._mouseUnselectable=this.element.attr("unselectable");this.element.attr("unselectable","on")}this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);(c.browser.msie&&this.element.attr("unselectable",this._mouseUnselectable))},_mouseDown:function(l){l.originalEvent=l.originalEvent||{};if(l.originalEvent.mouseHandled){return}(this._mouseStarted&&this._mouseUp(l));this._mouseDownEvent=l;var k=this,m=(l.which==1),j=(typeof this.options.cancel=="string"?c(l.target).parents().add(l.target).filter(this.options.cancel).length:false);if(!m||j||!this._mouseCapture(l)){return true}this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){k.mouseDelayMet=true},this.options.delay)}if(this._mouseDistanceMet(l)&&this._mouseDelayMet(l)){this._mouseStarted=(this._mouseStart(l)!==false);if(!this._mouseStarted){l.preventDefault();return true}}this._mouseMoveDelegate=function(n){return k._mouseMove(n)};this._mouseUpDelegate=function(n){return k._mouseUp(n)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);(c.browser.safari||l.preventDefault());l.originalEvent.mouseHandled=true;return true},_mouseMove:function(j){if(c.browser.msie&&!j.button){return this._mouseUp(j)}if(this._mouseStarted){this._mouseDrag(j);return j.preventDefault()}if(this._mouseDistanceMet(j)&&this._mouseDelayMet(j)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,j)!==false);(this._mouseStarted?this._mouseDrag(j):this._mouseUp(j))}return !this._mouseStarted},_mouseUp:function(j){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=(j.target==this._mouseDownEvent.target);this._mouseStop(j)}return false},_mouseDistanceMet:function(j){return(Math.max(Math.abs(this._mouseDownEvent.pageX-j.pageX),Math.abs(this._mouseDownEvent.pageY-j.pageY))>=this.options.distance)},_mouseDelayMet:function(j){return this.mouseDelayMet},_mouseStart:function(j){},_mouseDrag:function(j){},_mouseStop:function(j){},_mouseCapture:function(j){return true}};c.ui.mouse.defaults={cancel:null,distance:1,delay:0}})(jQuery);
(function(a){a.widget("ui.draggable",a.extend({},a.ui.mouse,{_init:function(){if(this.options.helper=="original"&&!(/^(?:r|a|f)/).test(this.element.css("position"))){this.element[0].style.position="relative"}(this.options.addClasses&&this.element.addClass("ui-draggable"));(this.options.disabled&&this.element.addClass("ui-draggable-disabled"));this._mouseInit()},destroy:function(){if(!this.element.data("draggable")){return}this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy()},_mouseCapture:function(b){var c=this.options;if(this.helper||c.disabled||a(b.target).is(".ui-resizable-handle")){return false}this.handle=this._getHandle(b);if(!this.handle){return false}return true},_mouseStart:function(b){var c=this.options;this.helper=this._createHelper(b);this._cacheHelperProportions();if(a.ui.ddmanager){a.ui.ddmanager.current=this}this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(b);this.originalPageX=b.pageX;this.originalPageY=b.pageY;if(c.cursorAt){this._adjustOffsetFromHelper(c.cursorAt)}if(c.containment){this._setContainment()}this._trigger("start",b);this._cacheHelperProportions();if(a.ui.ddmanager&&!c.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,b)}this.helper.addClass("ui-draggable-dragging");this._mouseDrag(b,true);return true},_mouseDrag:function(b,d){this.position=this._generatePosition(b);this.positionAbs=this._convertPositionTo("absolute");if(!d){var c=this._uiHash();this._trigger("drag",b,c);this.position=c.position}if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}if(a.ui.ddmanager){a.ui.ddmanager.drag(this,b)}return false},_mouseStop:function(c){var d=false;if(a.ui.ddmanager&&!this.options.dropBehaviour){d=a.ui.ddmanager.drop(this,c)}if(this.dropped){d=this.dropped;this.dropped=false}if((this.options.revert=="invalid"&&!d)||(this.options.revert=="valid"&&d)||this.options.revert===true||(a.isFunction(this.options.revert)&&this.options.revert.call(this.element,d))){var b=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){b._trigger("stop",c);b._clear()})}else{this._trigger("stop",c);this._clear()}return false},_getHandle:function(b){var c=!this.options.handle||!a(this.options.handle,this.element).length?true:false;a(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==b.target){c=true}});return c},_createHelper:function(c){var d=this.options;var b=a.isFunction(d.helper)?a(d.helper.apply(this.element[0],[c])):(d.helper=="clone"?this.element.clone():this.element);if(!b.parents("body").length){b.appendTo((d.appendTo=="parent"?this.element[0].parentNode:d.appendTo))}if(b[0]!=this.element[0]&&!(/(fixed|absolute)/).test(b.css("position"))){b.css("position","absolute")}return b},_adjustOffsetFromHelper:function(b){if(b.left!=undefined){this.offset.click.left=b.left+this.margins.left}if(b.right!=undefined){this.offset.click.left=this.helperProportions.width-b.right+this.margins.left}if(b.top!=undefined){this.offset.click.top=b.top+this.margins.top}if(b.bottom!=undefined){this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){b.left+=this.scrollParent.scrollLeft();b.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){b={top:0,left:0}}return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var b=this.element.position();return{top:b.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:b.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.element.css("marginLeft"),10)||0),top:(parseInt(this.element.css("marginTop"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e=this.options;if(e.containment=="parent"){e.containment=this.helper[0].parentNode}if(e.containment=="document"||e.containment=="window"){this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(e.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(e.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(e.containment)&&e.containment.constructor!=Array){var c=a(e.containment)[0];if(!c){return}var d=a(e.containment).offset();var b=(a(c).css("overflow")!="hidden");this.containment=[d.left+(parseInt(a(c).css("borderLeftWidth"),10)||0)+(parseInt(a(c).css("paddingLeft"),10)||0)-this.margins.left,d.top+(parseInt(a(c).css("borderTopWidth"),10)||0)+(parseInt(a(c).css("paddingTop"),10)||0)-this.margins.top,d.left+(b?Math.max(c.scrollWidth,c.offsetWidth):c.offsetWidth)-(parseInt(a(c).css("borderLeftWidth"),10)||0)-(parseInt(a(c).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,d.top+(b?Math.max(c.scrollHeight,c.offsetHeight):c.offsetHeight)-(parseInt(a(c).css("borderTopWidth"),10)||0)-(parseInt(a(c).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}else{if(e.containment.constructor==Array){this.containment=e.containment}}},_convertPositionTo:function(f,h){if(!h){h=this.position}var c=f=="absolute"?1:-1;var e=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=(/(html|body)/i).test(b[0].tagName);return{top:(h.top+this.offset.relative.top*c+this.offset.parent.top*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(g?0:b.scrollTop()))*c)),left:(h.left+this.offset.relative.left*c+this.offset.parent.left*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:b.scrollLeft())*c))}},_generatePosition:function(e){var h=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,i=(/(html|body)/i).test(b[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0])){this.offset.relative=this._getRelativeOffset()}var d=e.pageX;var c=e.pageY;if(this.originalPosition){if(this.containment){if(e.pageX-this.offset.click.left<this.containment[0]){d=this.containment[0]+this.offset.click.left}if(e.pageY-this.offset.click.top<this.containment[1]){c=this.containment[1]+this.offset.click.top}if(e.pageX-this.offset.click.left>this.containment[2]){d=this.containment[2]+this.offset.click.left}if(e.pageY-this.offset.click.top>this.containment[3]){c=this.containment[3]+this.offset.click.top}}if(h.grid){var g=this.originalPageY+Math.round((c-this.originalPageY)/h.grid[1])*h.grid[1];c=this.containment?(!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:(!(g-this.offset.click.top<this.containment[1])?g-h.grid[1]:g+h.grid[1])):g;var f=this.originalPageX+Math.round((d-this.originalPageX)/h.grid[0])*h.grid[0];d=this.containment?(!(f-this.offset.click.left<this.containment[0]||f-this.offset.click.left>this.containment[2])?f:(!(f-this.offset.click.left<this.containment[0])?f-h.grid[0]:f+h.grid[0])):f}}return{top:(c-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(i?0:b.scrollTop())))),left:(d-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:b.scrollLeft())))}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");if(this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval){this.helper.remove()}this.helper=null;this.cancelHelperRemoval=false},_trigger:function(b,c,d){d=d||this._uiHash();a.ui.plugin.call(this,b,[c,d]);if(b=="drag"){this.positionAbs=this._convertPositionTo("absolute")}return a.widget.prototype._trigger.call(this,b,c,d)},plugins:{},_uiHash:function(b){return{helper:this.helper,position:this.position,absolutePosition:this.positionAbs,offset:this.positionAbs}}}));a.extend(a.ui.draggable,{version:"1.7.1",eventPrefix:"drag",defaults:{addClasses:true,appendTo:"parent",axis:false,cancel:":input,option",connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,delay:0,distance:1,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false}});a.ui.plugin.add("draggable","connectToSortable",{start:function(c,e){var d=a(this).data("draggable"),f=d.options,b=a.extend({},e,{item:d.element});d.sortables=[];a(f.connectToSortable).each(function(){var g=a.data(this,"sortable");if(g&&!g.options.disabled){d.sortables.push({instance:g,shouldRevert:g.options.revert});g._refreshItems();g._trigger("activate",c,b)}})},stop:function(c,e){var d=a(this).data("draggable"),b=a.extend({},e,{item:d.element});a.each(d.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;d.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert){this.instance.options.revert=true}this.instance._mouseStop(c);this.instance.options.helper=this.instance.options._helper;if(d.options.helper=="original"){this.instance.currentItem.css({top:"auto",left:"auto"})}}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",c,b)}})},drag:function(c,f){var e=a(this).data("draggable"),b=this;var d=function(i){var n=this.offset.click.top,m=this.offset.click.left;var g=this.positionAbs.top,k=this.positionAbs.left;var j=i.height,l=i.width;var p=i.top,h=i.left;return a.ui.isOver(g+n,k+m,p,h,j,l)};a.each(e.sortables,function(g){this.instance.positionAbs=e.positionAbs;this.instance.helperProportions=e.helperProportions;this.instance.offset.click=e.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver=1;this.instance.currentItem=a(b).clone().appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return f.helper[0]};c.target=this.instance.currentItem[0];this.instance._mouseCapture(c,true);this.instance._mouseStart(c,true,true);this.instance.offset.click.top=e.offset.click.top;this.instance.offset.click.left=e.offset.click.left;this.instance.offset.parent.left-=e.offset.parent.left-this.instance.offset.parent.left;this.instance.offset.parent.top-=e.offset.parent.top-this.instance.offset.parent.top;e._trigger("toSortable",c);e.dropped=this.instance.element;e.currentItem=e.element;this.instance.fromOutside=e}if(this.instance.currentItem){this.instance._mouseDrag(c)}}else{if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",c,this.instance._uiHash(this.instance));this.instance._mouseStop(c,true);this.instance.options.helper=this.instance.options._helper;this.instance.currentItem.remove();if(this.instance.placeholder){this.instance.placeholder.remove()}e._trigger("fromSortable",c);e.dropped=false}}})}});a.ui.plugin.add("draggable","cursor",{start:function(c,d){var b=a("body"),e=a(this).data("draggable").options;if(b.css("cursor")){e._cursor=b.css("cursor")}b.css("cursor",e.cursor)},stop:function(b,c){var d=a(this).data("draggable").options;if(d._cursor){a("body").css("cursor",d._cursor)}}});a.ui.plugin.add("draggable","iframeFix",{start:function(b,c){var d=a(this).data("draggable").options;a(d.iframeFix===true?"iframe":d.iframeFix).each(function(){a('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1000}).css(a(this).offset()).appendTo("body")})},stop:function(b,c){a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)})}});a.ui.plugin.add("draggable","opacity",{start:function(c,d){var b=a(d.helper),e=a(this).data("draggable").options;if(b.css("opacity")){e._opacity=b.css("opacity")}b.css("opacity",e.opacity)},stop:function(b,c){var d=a(this).data("draggable").options;if(d._opacity){a(c.helper).css("opacity",d._opacity)}}});a.ui.plugin.add("draggable","scroll",{start:function(c,d){var b=a(this).data("draggable");if(b.scrollParent[0]!=document&&b.scrollParent[0].tagName!="HTML"){b.overflowOffset=b.scrollParent.offset()}},drag:function(d,e){var c=a(this).data("draggable"),f=c.options,b=false;if(c.scrollParent[0]!=document&&c.scrollParent[0].tagName!="HTML"){if(!f.axis||f.axis!="x"){if((c.overflowOffset.top+c.scrollParent[0].offsetHeight)-d.pageY<f.scrollSensitivity){c.scrollParent[0].scrollTop=b=c.scrollParent[0].scrollTop+f.scrollSpeed}else{if(d.pageY-c.overflowOffset.top<f.scrollSensitivity){c.scrollParent[0].scrollTop=b=c.scrollParent[0].scrollTop-f.scrollSpeed}}}if(!f.axis||f.axis!="y"){if((c.overflowOffset.left+c.scrollParent[0].offsetWidth)-d.pageX<f.scrollSensitivity){c.scrollParent[0].scrollLeft=b=c.scrollParent[0].scrollLeft+f.scrollSpeed}else{if(d.pageX-c.overflowOffset.left<f.scrollSensitivity){c.scrollParent[0].scrollLeft=b=c.scrollParent[0].scrollLeft-f.scrollSpeed}}}}else{if(!f.axis||f.axis!="x"){if(d.pageY-a(document).scrollTop()<f.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()-f.scrollSpeed)}else{if(a(window).height()-(d.pageY-a(document).scrollTop())<f.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()+f.scrollSpeed)}}}if(!f.axis||f.axis!="y"){if(d.pageX-a(document).scrollLeft()<f.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()-f.scrollSpeed)}else{if(a(window).width()-(d.pageX-a(document).scrollLeft())<f.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()+f.scrollSpeed)}}}}if(b!==false&&a.ui.ddmanager&&!f.dropBehaviour){a.ui.ddmanager.prepareOffsets(c,d)}}});a.ui.plugin.add("draggable","snap",{start:function(c,d){var b=a(this).data("draggable"),e=b.options;b.snapElements=[];a(e.snap.constructor!=String?(e.snap.items||":data(draggable)"):e.snap).each(function(){var g=a(this);var f=g.offset();if(this!=b.element[0]){b.snapElements.push({item:this,width:g.outerWidth(),height:g.outerHeight(),top:f.top,left:f.left})}})},drag:function(u,p){var g=a(this).data("draggable"),q=g.options;var y=q.snapTolerance;var x=p.offset.left,w=x+g.helperProportions.width,f=p.offset.top,e=f+g.helperProportions.height;for(var v=g.snapElements.length-1;v>=0;v--){var s=g.snapElements[v].left,n=s+g.snapElements[v].width,m=g.snapElements[v].top,A=m+g.snapElements[v].height;if(!((s-y<x&&x<n+y&&m-y<f&&f<A+y)||(s-y<x&&x<n+y&&m-y<e&&e<A+y)||(s-y<w&&w<n+y&&m-y<f&&f<A+y)||(s-y<w&&w<n+y&&m-y<e&&e<A+y))){if(g.snapElements[v].snapping){(g.options.snap.release&&g.options.snap.release.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=false;continue}if(q.snapMode!="inner"){var c=Math.abs(m-e)<=y;var z=Math.abs(A-f)<=y;var j=Math.abs(s-w)<=y;var k=Math.abs(n-x)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m-g.helperProportions.height,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s-g.helperProportions.width}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n}).left-g.margins.left}}var h=(c||z||j||k);if(q.snapMode!="outer"){var c=Math.abs(m-f)<=y;var z=Math.abs(A-e)<=y;var j=Math.abs(s-x)<=y;var k=Math.abs(n-w)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A-g.helperProportions.height,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n-g.helperProportions.width}).left-g.margins.left}}if(!g.snapElements[v].snapping&&(c||z||j||k||h)){(g.options.snap.snap&&g.options.snap.snap.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=(c||z||j||k||h)}}});a.ui.plugin.add("draggable","stack",{start:function(b,c){var e=a(this).data("draggable").options;var d=a.makeArray(a(e.stack.group)).sort(function(g,f){return(parseInt(a(g).css("zIndex"),10)||e.stack.min)-(parseInt(a(f).css("zIndex"),10)||e.stack.min)});a(d).each(function(f){this.style.zIndex=e.stack.min+f});this[0].style.zIndex=e.stack.min+d.length}});a.ui.plugin.add("draggable","zIndex",{start:function(c,d){var b=a(d.helper),e=a(this).data("draggable").options;if(b.css("zIndex")){e._zIndex=b.css("zIndex")}b.css("zIndex",e.zIndex)},stop:function(b,c){var d=a(this).data("draggable").options;if(d._zIndex){a(c.helper).css("zIndex",d._zIndex)}}})})(jQuery);
(function(a){a.widget("ui.sortable",a.extend({},a.ui.mouse,{_init:function(){var b=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?(/left|right/).test(this.items[0].item.css("float")):false;this.offset=this.element.offset();this._mouseInit()},destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").removeData("sortable").unbind(".sortable");this._mouseDestroy();for(var b=this.items.length-1;b>=0;b--){this.items[b].item.removeData("sortable-item")}},_mouseCapture:function(e,f){if(this.reverting){return false}if(this.options.disabled||this.options.type=="static"){return false}this._refreshItems(e);var d=null,c=this,b=a(e.target).parents().each(function(){if(a.data(this,"sortable-item")==c){d=a(this);return false}});if(a.data(e.target,"sortable-item")==c){d=a(e.target)}if(!d){return false}if(this.options.handle&&!f){var g=false;a(this.options.handle,d).find("*").andSelf().each(function(){if(this==e.target){g=true}});if(!g){return false}}this.currentItem=d;this._removeCurrentsFromItems();return true},_mouseStart:function(e,f,b){var g=this.options,c=this;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(e);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");a.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(e);this.originalPageX=e.pageX;this.originalPageY=e.pageY;if(g.cursorAt){this._adjustOffsetFromHelper(g.cursorAt)}this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};if(this.helper[0]!=this.currentItem[0]){this.currentItem.hide()}this._createPlaceholder();if(g.containment){this._setContainment()}if(g.cursor){if(a("body").css("cursor")){this._storedCursor=a("body").css("cursor")}a("body").css("cursor",g.cursor)}if(g.opacity){if(this.helper.css("opacity")){this._storedOpacity=this.helper.css("opacity")}this.helper.css("opacity",g.opacity)}if(g.zIndex){if(this.helper.css("zIndex")){this._storedZIndex=this.helper.css("zIndex")}this.helper.css("zIndex",g.zIndex)}if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){this.overflowOffset=this.scrollParent.offset()}this._trigger("start",e,this._uiHash());if(!this._preserveHelperProportions){this._cacheHelperProportions()}if(!b){for(var d=this.containers.length-1;d>=0;d--){this.containers[d]._trigger("activate",e,c._uiHash(this))}}if(a.ui.ddmanager){a.ui.ddmanager.current=this}if(a.ui.ddmanager&&!g.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,e)}this.dragging=true;this.helper.addClass("ui-sortable-helper");this._mouseDrag(e);return true},_mouseDrag:function(f){this.position=this._generatePosition(f);this.positionAbs=this._convertPositionTo("absolute");if(!this.lastPositionAbs){this.lastPositionAbs=this.positionAbs}if(this.options.scroll){var g=this.options,b=false;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){if((this.overflowOffset.top+this.scrollParent[0].offsetHeight)-f.pageY<g.scrollSensitivity){this.scrollParent[0].scrollTop=b=this.scrollParent[0].scrollTop+g.scrollSpeed}else{if(f.pageY-this.overflowOffset.top<g.scrollSensitivity){this.scrollParent[0].scrollTop=b=this.scrollParent[0].scrollTop-g.scrollSpeed}}if((this.overflowOffset.left+this.scrollParent[0].offsetWidth)-f.pageX<g.scrollSensitivity){this.scrollParent[0].scrollLeft=b=this.scrollParent[0].scrollLeft+g.scrollSpeed}else{if(f.pageX-this.overflowOffset.left<g.scrollSensitivity){this.scrollParent[0].scrollLeft=b=this.scrollParent[0].scrollLeft-g.scrollSpeed}}}else{if(f.pageY-a(document).scrollTop()<g.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()-g.scrollSpeed)}else{if(a(window).height()-(f.pageY-a(document).scrollTop())<g.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()+g.scrollSpeed)}}if(f.pageX-a(document).scrollLeft()<g.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()-g.scrollSpeed)}else{if(a(window).width()-(f.pageX-a(document).scrollLeft())<g.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()+g.scrollSpeed)}}}if(b!==false&&a.ui.ddmanager&&!g.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,f)}}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}for(var d=this.items.length-1;d>=0;d--){var e=this.items[d],c=e.item[0],h=this._intersectsWithPointer(e);if(!h){continue}if(c!=this.currentItem[0]&&this.placeholder[h==1?"next":"prev"]()[0]!=c&&!a.ui.contains(this.placeholder[0],c)&&(this.options.type=="semi-dynamic"?!a.ui.contains(this.element[0],c):true)){this.direction=h==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(e)){this._rearrange(f,e)}else{break}this._trigger("change",f,this._uiHash());break}}this._contactContainers(f);if(a.ui.ddmanager){a.ui.ddmanager.drag(this,f)}this._trigger("sort",f,this._uiHash());this.lastPositionAbs=this.positionAbs;return false},_mouseStop:function(c,d){if(!c){return}if(a.ui.ddmanager&&!this.options.dropBehaviour){a.ui.ddmanager.drop(this,c)}if(this.options.revert){var b=this;var e=b.placeholder.offset();b.reverting=true;a(this.helper).animate({left:e.left-this.offset.parent.left-b.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:e.top-this.offset.parent.top-b.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){b._clear(c)})}else{this._clear(c,d)}return false},cancel:function(){var b=this;if(this.dragging){this._mouseUp();if(this.options.helper=="original"){this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}for(var c=this.containers.length-1;c>=0;c--){this.containers[c]._trigger("deactivate",null,b._uiHash(this));if(this.containers[c].containerCache.over){this.containers[c]._trigger("out",null,b._uiHash(this));this.containers[c].containerCache.over=0}}}if(this.placeholder[0].parentNode){this.placeholder[0].parentNode.removeChild(this.placeholder[0])}if(this.options.helper!="original"&&this.helper&&this.helper[0].parentNode){this.helper.remove()}a.extend(this,{helper:null,dragging:false,reverting:false,_noFinalSort:null});if(this.domPosition.prev){a(this.domPosition.prev).after(this.currentItem)}else{a(this.domPosition.parent).prepend(this.currentItem)}return true},serialize:function(d){var b=this._getItemsAsjQuery(d&&d.connected);var c=[];d=d||{};a(b).each(function(){var e=(a(d.item||this).attr(d.attribute||"id")||"").match(d.expression||(/(.+)[-=_](.+)/));if(e){c.push((d.key||e[1]+"[]")+"="+(d.key&&d.expression?e[1]:e[2]))}});return c.join("&")},toArray:function(d){var b=this._getItemsAsjQuery(d&&d.connected);var c=[];d=d||{};b.each(function(){c.push(a(d.item||this).attr(d.attribute||"id")||"")});return c},_intersectsWith:function(m){var e=this.positionAbs.left,d=e+this.helperProportions.width,k=this.positionAbs.top,j=k+this.helperProportions.height;var f=m.left,c=f+m.width,n=m.top,i=n+m.height;var o=this.offset.click.top,h=this.offset.click.left;var g=(k+o)>n&&(k+o)<i&&(e+h)>f&&(e+h)<c;if(this.options.tolerance=="pointer"||this.options.forcePointerForContainers||(this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>m[this.floating?"width":"height"])){return g}else{return(f<e+(this.helperProportions.width/2)&&d-(this.helperProportions.width/2)<c&&n<k+(this.helperProportions.height/2)&&j-(this.helperProportions.height/2)<i)}},_intersectsWithPointer:function(d){var e=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,d.top,d.height),c=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,d.left,d.width),g=e&&c,b=this._getDragVerticalDirection(),f=this._getDragHorizontalDirection();if(!g){return false}return this.floating?(((f&&f=="right")||b=="down")?2:1):(b&&(b=="down"?2:1))},_intersectsWithSides:function(e){var c=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,e.top+(e.height/2),e.height),d=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,e.left+(e.width/2),e.width),b=this._getDragVerticalDirection(),f=this._getDragHorizontalDirection();if(this.floating&&f){return((f=="right"&&d)||(f=="left"&&!d))}else{return b&&((b=="down"&&c)||(b=="up"&&!c))}},_getDragVerticalDirection:function(){var b=this.positionAbs.top-this.lastPositionAbs.top;return b!=0&&(b>0?"down":"up")},_getDragHorizontalDirection:function(){var b=this.positionAbs.left-this.lastPositionAbs.left;return b!=0&&(b>0?"right":"left")},refresh:function(b){this._refreshItems(b);this.refreshPositions()},_connectWith:function(){var b=this.options;return b.connectWith.constructor==String?[b.connectWith]:b.connectWith},_getItemsAsjQuery:function(b){var l=this;var g=[];var e=[];var h=this._connectWith();if(h&&b){for(var d=h.length-1;d>=0;d--){var k=a(h[d]);for(var c=k.length-1;c>=0;c--){var f=a.data(k[c],"sortable");if(f&&f!=this&&!f.options.disabled){e.push([a.isFunction(f.options.items)?f.options.items.call(f.element):a(f.options.items,f.element).not(".ui-sortable-helper"),f])}}}}e.push([a.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):a(this.options.items,this.element).not(".ui-sortable-helper"),this]);for(var d=e.length-1;d>=0;d--){e[d][0].each(function(){g.push(this)})}return a(g)},_removeCurrentsFromItems:function(){var d=this.currentItem.find(":data(sortable-item)");for(var c=0;c<this.items.length;c++){for(var b=0;b<d.length;b++){if(d[b]==this.items[c].item[0]){this.items.splice(c,1)}}}},_refreshItems:function(b){this.items=[];this.containers=[this];var h=this.items;var p=this;var f=[[a.isFunction(this.options.items)?this.options.items.call(this.element[0],b,{item:this.currentItem}):a(this.options.items,this.element),this]];var l=this._connectWith();if(l){for(var e=l.length-1;e>=0;e--){var m=a(l[e]);for(var d=m.length-1;d>=0;d--){var g=a.data(m[d],"sortable");if(g&&g!=this&&!g.options.disabled){f.push([a.isFunction(g.options.items)?g.options.items.call(g.element[0],b,{item:this.currentItem}):a(g.options.items,g.element),g]);this.containers.push(g)}}}}for(var e=f.length-1;e>=0;e--){var k=f[e][1];var c=f[e][0];for(var d=0,n=c.length;d<n;d++){var o=a(c[d]);o.data("sortable-item",k);h.push({item:o,instance:k,width:0,height:0,left:0,top:0})}}},refreshPositions:function(b){if(this.offsetParent&&this.helper){this.offset.parent=this._getParentOffset()}for(var d=this.items.length-1;d>=0;d--){var e=this.items[d];if(e.instance!=this.currentContainer&&this.currentContainer&&e.item[0]!=this.currentItem[0]){continue}var c=this.options.toleranceElement?a(this.options.toleranceElement,e.item):e.item;if(!b){e.width=c.outerWidth();e.height=c.outerHeight()}var f=c.offset();e.left=f.left;e.top=f.top}if(this.options.custom&&this.options.custom.refreshContainers){this.options.custom.refreshContainers.call(this)}else{for(var d=this.containers.length-1;d>=0;d--){var f=this.containers[d].element.offset();this.containers[d].containerCache.left=f.left;this.containers[d].containerCache.top=f.top;this.containers[d].containerCache.width=this.containers[d].element.outerWidth();this.containers[d].containerCache.height=this.containers[d].element.outerHeight()}}},_createPlaceholder:function(d){var b=d||this,e=b.options;if(!e.placeholder||e.placeholder.constructor==String){var c=e.placeholder;e.placeholder={element:function(){var f=a(document.createElement(b.currentItem[0].nodeName)).addClass(c||b.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];if(!c){f.style.visibility="hidden"}return f},update:function(f,g){if(c&&!e.forcePlaceholderSize){return}if(!g.height()){g.height(b.currentItem.innerHeight()-parseInt(b.currentItem.css("paddingTop")||0,10)-parseInt(b.currentItem.css("paddingBottom")||0,10))}if(!g.width()){g.width(b.currentItem.innerWidth()-parseInt(b.currentItem.css("paddingLeft")||0,10)-parseInt(b.currentItem.css("paddingRight")||0,10))}}}}b.placeholder=a(e.placeholder.element.call(b.element,b.currentItem));b.currentItem.after(b.placeholder);e.placeholder.update(b,b.placeholder)},_contactContainers:function(d){for(var c=this.containers.length-1;c>=0;c--){if(this._intersectsWith(this.containers[c].containerCache)){if(!this.containers[c].containerCache.over){if(this.currentContainer!=this.containers[c]){var h=10000;var g=null;var e=this.positionAbs[this.containers[c].floating?"left":"top"];for(var b=this.items.length-1;b>=0;b--){if(!a.ui.contains(this.containers[c].element[0],this.items[b].item[0])){continue}var f=this.items[b][this.containers[c].floating?"left":"top"];if(Math.abs(f-e)<h){h=Math.abs(f-e);g=this.items[b]}}if(!g&&!this.options.dropOnEmpty){continue}this.currentContainer=this.containers[c];g?this._rearrange(d,g,null,true):this._rearrange(d,null,this.containers[c].element,true);this._trigger("change",d,this._uiHash());this.containers[c]._trigger("change",d,this._uiHash(this));this.options.placeholder.update(this.currentContainer,this.placeholder)}this.containers[c]._trigger("over",d,this._uiHash(this));this.containers[c].containerCache.over=1}}else{if(this.containers[c].containerCache.over){this.containers[c]._trigger("out",d,this._uiHash(this));this.containers[c].containerCache.over=0}}}},_createHelper:function(c){var d=this.options;var b=a.isFunction(d.helper)?a(d.helper.apply(this.element[0],[c,this.currentItem])):(d.helper=="clone"?this.currentItem.clone():this.currentItem);if(!b.parents("body").length){a(d.appendTo!="parent"?d.appendTo:this.currentItem[0].parentNode)[0].appendChild(b[0])}if(b[0]==this.currentItem[0]){this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}}if(b[0].style.width==""||d.forceHelperSize){b.width(this.currentItem.width())}if(b[0].style.height==""||d.forceHelperSize){b.height(this.currentItem.height())}return b},_adjustOffsetFromHelper:function(b){if(b.left!=undefined){this.offset.click.left=b.left+this.margins.left}if(b.right!=undefined){this.offset.click.left=this.helperProportions.width-b.right+this.margins.left}if(b.top!=undefined){this.offset.click.top=b.top+this.margins.top}if(b.bottom!=undefined){this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){b.left+=this.scrollParent.scrollLeft();b.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){b={top:0,left:0}}return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var b=this.currentItem.position();return{top:b.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:b.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.currentItem.css("marginLeft"),10)||0),top:(parseInt(this.currentItem.css("marginTop"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e=this.options;if(e.containment=="parent"){e.containment=this.helper[0].parentNode}if(e.containment=="document"||e.containment=="window"){this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(e.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(e.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(e.containment)){var c=a(e.containment)[0];var d=a(e.containment).offset();var b=(a(c).css("overflow")!="hidden");this.containment=[d.left+(parseInt(a(c).css("borderLeftWidth"),10)||0)+(parseInt(a(c).css("paddingLeft"),10)||0)-this.margins.left,d.top+(parseInt(a(c).css("borderTopWidth"),10)||0)+(parseInt(a(c).css("paddingTop"),10)||0)-this.margins.top,d.left+(b?Math.max(c.scrollWidth,c.offsetWidth):c.offsetWidth)-(parseInt(a(c).css("borderLeftWidth"),10)||0)-(parseInt(a(c).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,d.top+(b?Math.max(c.scrollHeight,c.offsetHeight):c.offsetHeight)-(parseInt(a(c).css("borderTopWidth"),10)||0)-(parseInt(a(c).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(f,h){if(!h){h=this.position}var c=f=="absolute"?1:-1;var e=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=(/(html|body)/i).test(b[0].tagName);return{top:(h.top+this.offset.relative.top*c+this.offset.parent.top*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(g?0:b.scrollTop()))*c)),left:(h.left+this.offset.relative.left*c+this.offset.parent.left*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:b.scrollLeft())*c))}},_generatePosition:function(e){var h=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,i=(/(html|body)/i).test(b[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0])){this.offset.relative=this._getRelativeOffset()}var d=e.pageX;var c=e.pageY;if(this.originalPosition){if(this.containment){if(e.pageX-this.offset.click.left<this.containment[0]){d=this.containment[0]+this.offset.click.left}if(e.pageY-this.offset.click.top<this.containment[1]){c=this.containment[1]+this.offset.click.top}if(e.pageX-this.offset.click.left>this.containment[2]){d=this.containment[2]+this.offset.click.left}if(e.pageY-this.offset.click.top>this.containment[3]){c=this.containment[3]+this.offset.click.top}}if(h.grid){var g=this.originalPageY+Math.round((c-this.originalPageY)/h.grid[1])*h.grid[1];c=this.containment?(!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:(!(g-this.offset.click.top<this.containment[1])?g-h.grid[1]:g+h.grid[1])):g;var f=this.originalPageX+Math.round((d-this.originalPageX)/h.grid[0])*h.grid[0];d=this.containment?(!(f-this.offset.click.left<this.containment[0]||f-this.offset.click.left>this.containment[2])?f:(!(f-this.offset.click.left<this.containment[0])?f-h.grid[0]:f+h.grid[0])):f}}return{top:(c-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(i?0:b.scrollTop())))),left:(d-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:b.scrollLeft())))}},_rearrange:function(g,f,c,e){c?c[0].appendChild(this.placeholder[0]):f.item[0].parentNode.insertBefore(this.placeholder[0],(this.direction=="down"?f.item[0]:f.item[0].nextSibling));this.counter=this.counter?++this.counter:1;var d=this,b=this.counter;window.setTimeout(function(){if(b==d.counter){d.refreshPositions(!e)}},0)},_clear:function(d,e){this.reverting=false;var f=[],b=this;if(!this._noFinalSort&&this.currentItem[0].parentNode){this.placeholder.before(this.currentItem)}this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var c in this._storedCSS){if(this._storedCSS[c]=="auto"||this._storedCSS[c]=="static"){this._storedCSS[c]=""}}this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}if(this.fromOutside&&!e){f.push(function(g){this._trigger("receive",g,this._uiHash(this.fromOutside))})}if((this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!e){f.push(function(g){this._trigger("update",g,this._uiHash())})}if(!a.ui.contains(this.element[0],this.currentItem[0])){if(!e){f.push(function(g){this._trigger("remove",g,this._uiHash())})}for(var c=this.containers.length-1;c>=0;c--){if(a.ui.contains(this.containers[c].element[0],this.currentItem[0])&&!e){f.push((function(g){return function(h){g._trigger("receive",h,this._uiHash(this))}}).call(this,this.containers[c]));f.push((function(g){return function(h){g._trigger("update",h,this._uiHash(this))}}).call(this,this.containers[c]))}}}for(var c=this.containers.length-1;c>=0;c--){if(!e){f.push((function(g){return function(h){g._trigger("deactivate",h,this._uiHash(this))}}).call(this,this.containers[c]))}if(this.containers[c].containerCache.over){f.push((function(g){return function(h){g._trigger("out",h,this._uiHash(this))}}).call(this,this.containers[c]));this.containers[c].containerCache.over=0}}if(this._storedCursor){a("body").css("cursor",this._storedCursor)}if(this._storedOpacity){this.helper.css("opacity",this._storedOpacity)}if(this._storedZIndex){this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex)}this.dragging=false;if(this.cancelHelperRemoval){if(!e){this._trigger("beforeStop",d,this._uiHash());for(var c=0;c<f.length;c++){f[c].call(this,d)}this._trigger("stop",d,this._uiHash())}return false}if(!e){this._trigger("beforeStop",d,this._uiHash())}this.placeholder[0].parentNode.removeChild(this.placeholder[0]);if(this.helper[0]!=this.currentItem[0]){this.helper.remove()}this.helper=null;if(!e){for(var c=0;c<f.length;c++){f[c].call(this,d)}this._trigger("stop",d,this._uiHash())}this.fromOutside=false;return true},_trigger:function(){if(a.widget.prototype._trigger.apply(this,arguments)===false){this.cancel()}},_uiHash:function(c){var b=c||this;return{helper:b.helper,placeholder:b.placeholder||a([]),position:b.position,absolutePosition:b.positionAbs,offset:b.positionAbs,item:b.currentItem,sender:c?c.element:null}}}));a.extend(a.ui.sortable,{getter:"serialize toArray",version:"1.7.1",eventPrefix:"sort",defaults:{appendTo:"parent",axis:false,cancel:":input,option",connectWith:false,containment:false,cursor:"auto",cursorAt:false,delay:0,distance:1,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:"> *",opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1000}})})(jQuery);
jQuery.noConflict();

(function($) {

  this.GLOBAL = {
    debug: true,

    // Глобальный объект для переинициализации всего,
    // в ответ на аякс например
    aInit: [],
    reInit: function(func){
      try{
        if(func && $.isFunction(func)){
          func.call();
          this.aInit.push(func);
        } else {
          $.each(this.aInit, function(){
            this.call();
          })
        }
      } catch(e){
        debug(e);
      }
    }
  }

  this.debug = function(str) {
  	if (window.console && window.console.log && GLOBAL.debug)
  	window.console.log("[GLOBAL: '" + str + "']\n" + debug.caller.toString());
  };
  
  if( typeof(String.prototype.trim) === "undefined" ) {
    String.prototype.trim = function(){
      return String(this).replace(/^\s+|\s+$/g, '');
    };
  }  

})(jQuery);

var Prototype={Version:"1.6.0.2",Browser:{IE:!!(window.attachEvent&&!window.opera),Opera:!!window.opera,WebKit:navigator.userAgent.indexOf("AppleWebKit/")>-1,Gecko:navigator.userAgent.indexOf("Gecko")>-1&&navigator.userAgent.indexOf("KHTML")==-1,MobileSafari:!!navigator.userAgent.match(/Apple.*Mobile.*Safari/)},BrowserFeatures:{XPath:!!document.evaluate,ElementExtensions:!!window.HTMLElement,SpecificElementExtensions:document.createElement("div").__proto__&&document.createElement("div").__proto__!==document.createElement("form").__proto__},ScriptFragment:"<script[^>]*>([\\S\\s]*?)<\/script>",JSONFilter:/^\/\*-secure-([\s\S]*)\*\/\s*$/,emptyFunction:function(){},K:function(a){return a}};if(Prototype.Browser.MobileSafari){Prototype.BrowserFeatures.SpecificElementExtensions=false}var Class={create:function(){var e=null,d=$A(arguments);if(Object.isFunction(d[0])){e=d.shift()}function a(){this.initialize.apply(this,arguments)}Object.extend(a,Class.Methods);a.superclass=e;a.subclasses=[];if(e){var b=function(){};b.prototype=e.prototype;a.prototype=new b;e.subclasses.push(a)}for(var c=0;c<d.length;c++){a.addMethods(d[c])}if(!a.prototype.initialize){a.prototype.initialize=Prototype.emptyFunction}a.prototype.constructor=a;return a}};Class.Methods={addMethods:function(g){var c=this.superclass&&this.superclass.prototype;var b=Object.keys(g);if(!Object.keys({toString:true}).length){b.push("toString","valueOf")}for(var a=0,d=b.length;a<d;a++){var f=b[a],e=g[f];if(c&&Object.isFunction(e)&&e.argumentNames().first()=="$super"){var h=e,e=Object.extend((function(i){return function(){return c[i].apply(this,arguments)}})(f).wrap(h),{valueOf:function(){return h},toString:function(){return h.toString()}})}this.prototype[f]=e}return this}};var Abstract={};Object.extend=function(a,c){for(var b in c){a[b]=c[b]}return a};Object.extend(Object,{inspect:function(a){try{if(Object.isUndefined(a)){return"undefined"}if(a===null){return"null"}return a.inspect?a.inspect():String(a)}catch(b){if(b instanceof RangeError){return"..."}throw b}},toJSON:function(a){var c=typeof a;switch(c){case"undefined":case"function":case"unknown":return;case"boolean":return a.toString()}if(a===null){return"null"}if(a.toJSON){return a.toJSON()}if(Object.isElement(a)){return}var b=[];for(var e in a){var d=Object.toJSON(a[e]);if(!Object.isUndefined(d)){b.push(e.toJSON()+": "+d)}}return"{"+b.join(", ")+"}"},toQueryString:function(a){return $H(a).toQueryString()},toHTML:function(a){return a&&a.toHTML?a.toHTML():String.interpret(a)},keys:function(a){var b=[];for(var c in a){b.push(c)}return b},values:function(b){var a=[];for(var c in b){a.push(b[c])}return a},clone:function(a){return Object.extend({},a)},isElement:function(a){return a&&a.nodeType==1},isArray:function(a){return a!=null&&typeof a=="object"&&"splice" in a&&"join" in a},isHash:function(a){return a instanceof Hash},isFunction:function(a){return typeof a=="function"},isString:function(a){return typeof a=="string"},isNumber:function(a){return typeof a=="number"},isUndefined:function(a){return typeof a=="undefined"}});Object.extend(Function.prototype,{argumentNames:function(){var a=this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");return a.length==1&&!a[0]?[]:a},bind:function(){if(arguments.length<2&&Object.isUndefined(arguments[0])){return this}var a=this,c=$A(arguments),b=c.shift();return function(){return a.apply(b,c.concat($A(arguments)))}},bindAsEventListener:function(){var a=this,c=$A(arguments),b=c.shift();return function(d){return a.apply(b,[d||window.event].concat(c))}},curry:function(){if(!arguments.length){return this}var a=this,b=$A(arguments);return function(){return a.apply(this,b.concat($A(arguments)))}},delay:function(){var a=this,b=$A(arguments),c=b.shift()*1000;return window.setTimeout(function(){return a.apply(a,b)},c)},wrap:function(b){var a=this;return function(){return b.apply(this,[a.bind(this)].concat($A(arguments)))}},methodize:function(){if(this._methodized){return this._methodized}var a=this;return this._methodized=function(){return a.apply(null,[this].concat($A(arguments)))}}});Function.prototype.defer=Function.prototype.delay.curry(0.01);Date.prototype.toJSON=function(){return'"'+this.getUTCFullYear()+"-"+(this.getUTCMonth()+1).toPaddedString(2)+"-"+this.getUTCDate().toPaddedString(2)+"T"+this.getUTCHours().toPaddedString(2)+":"+this.getUTCMinutes().toPaddedString(2)+":"+this.getUTCSeconds().toPaddedString(2)+'Z"'};var Try={these:function(){var c;for(var b=0,d=arguments.length;b<d;b++){var a=arguments[b];try{c=a();break}catch(f){}}return c}};RegExp.prototype.match=RegExp.prototype.test;RegExp.escape=function(a){return String(a).replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")};var PeriodicalExecuter=Class.create({initialize:function(b,a){this.callback=b;this.frequency=a;this.currentlyExecuting=false;this.registerCallback()},registerCallback:function(){this.timer=setInterval(this.onTimerEvent.bind(this),this.frequency*1000)},execute:function(){this.callback(this)},stop:function(){if(!this.timer){return}clearInterval(this.timer);this.timer=null},onTimerEvent:function(){if(!this.currentlyExecuting){try{this.currentlyExecuting=true;this.execute()}finally{this.currentlyExecuting=false}}}});Object.extend(String,{interpret:function(a){return a==null?"":String(a)},specialChar:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r","\\":"\\\\"}});Object.extend(String.prototype,{gsub:function(e,c){var a="",d=this,b;c=arguments.callee.prepareReplacement(c);while(d.length>0){if(b=d.match(e)){a+=d.slice(0,b.index);a+=String.interpret(c(b));d=d.slice(b.index+b[0].length)}else{a+=d,d=""}}return a},sub:function(c,a,b){a=this.gsub.prepareReplacement(a);b=Object.isUndefined(b)?1:b;return this.gsub(c,function(d){if(--b<0){return d[0]}return a(d)})},scan:function(b,a){this.gsub(b,a);return String(this)},truncate:function(b,a){b=b||30;a=Object.isUndefined(a)?"...":a;return this.length>b?this.slice(0,b-a.length)+a:String(this)},strip:function(){return this.replace(/^\s+/,"").replace(/\s+$/,"")},stripTags:function(){return this.replace(/<\/?[^>]+>/gi,"")},stripScripts:function(){return this.replace(new RegExp(Prototype.ScriptFragment,"img"),"")},extractScripts:function(){var b=new RegExp(Prototype.ScriptFragment,"img");var a=new RegExp(Prototype.ScriptFragment,"im");return(this.match(b)||[]).map(function(c){return(c.match(a)||["",""])[1]})},evalScripts:function(){return this.extractScripts().map(function(script){return eval(script)})},escapeHTML:function(){var a=arguments.callee;a.text.data=this;return a.div.innerHTML},unescapeHTML:function(){var a=new Element("div");a.innerHTML=this.stripTags();return a.childNodes[0]?(a.childNodes.length>1?$A(a.childNodes).inject("",function(b,c){return b+c.nodeValue}):a.childNodes[0].nodeValue):""},toQueryParams:function(b){var a=this.strip().match(/([^?#]*)(#.*)?$/);if(!a){return{}}return a[1].split(b||"&").inject({},function(e,f){if((f=f.split("="))[0]){var c=decodeURIComponent(f.shift());var d=f.length>1?f.join("="):f[0];if(d!=undefined){d=decodeURIComponent(d)}if(c in e){if(!Object.isArray(e[c])){e[c]=[e[c]]}e[c].push(d)}else{e[c]=d}}return e})},toArray:function(){return this.split("")},succ:function(){return this.slice(0,this.length-1)+String.fromCharCode(this.charCodeAt(this.length-1)+1)},times:function(a){return a<1?"":new Array(a+1).join(this)},camelize:function(){var d=this.split("-"),a=d.length;if(a==1){return d[0]}var c=this.charAt(0)=="-"?d[0].charAt(0).toUpperCase()+d[0].substring(1):d[0];for(var b=1;b<a;b++){c+=d[b].charAt(0).toUpperCase()+d[b].substring(1)}return c},capitalize:function(){return this.charAt(0).toUpperCase()+this.substring(1).toLowerCase()},underscore:function(){return this.gsub(/::/,"/").gsub(/([A-Z]+)([A-Z][a-z])/,"#{1}_#{2}").gsub(/([a-z\d])([A-Z])/,"#{1}_#{2}").gsub(/-/,"_").toLowerCase()},dasherize:function(){return this.gsub(/_/,"-")},inspect:function(b){var a=this.gsub(/[\x00-\x1f\\]/,function(c){var d=String.specialChar[c[0]];return d?d:"\\u00"+c[0].charCodeAt().toPaddedString(2,16)});if(b){return'"'+a.replace(/"/g,'\\"')+'"'}return"'"+a.replace(/'/g,"\\'")+"'"},toJSON:function(){return this.inspect(true)},unfilterJSON:function(a){return this.sub(a||Prototype.JSONFilter,"#{1}")},isJSON:function(){var a=this;if(a.blank()){return false}a=this.replace(/\\./g,"@").replace(/"[^"\\\n\r]*"/g,"");return(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(a)},evalJSON:function(sanitize){var json=this.unfilterJSON();try{if(!sanitize||json.isJSON()){return eval("("+json+")")}}catch(e){}throw new SyntaxError("Badly formed JSON string: "+this.inspect())},include:function(a){return this.indexOf(a)>-1},startsWith:function(a){return this.indexOf(a)===0},endsWith:function(a){var b=this.length-a.length;return b>=0&&this.lastIndexOf(a)===b},empty:function(){return this==""},blank:function(){return/^\s*$/.test(this)},interpolate:function(a,b){return new Template(this,b).evaluate(a)}});if(Prototype.Browser.WebKit||Prototype.Browser.IE){Object.extend(String.prototype,{escapeHTML:function(){return this.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")},unescapeHTML:function(){return this.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">")}})}String.prototype.gsub.prepareReplacement=function(b){if(Object.isFunction(b)){return b}var a=new Template(b);return function(c){return a.evaluate(c)}};String.prototype.parseQuery=String.prototype.toQueryParams;Object.extend(String.prototype.escapeHTML,{div:document.createElement("div"),text:document.createTextNode("")});with(String.prototype.escapeHTML){div.appendChild(text)}var Template=Class.create({initialize:function(a,b){this.template=a.toString();this.pattern=b||Template.Pattern},evaluate:function(a){if(Object.isFunction(a.toTemplateReplacements)){a=a.toTemplateReplacements()}return this.template.gsub(this.pattern,function(d){if(a==null){return""}var f=d[1]||"";if(f=="\\"){return d[2]}var b=a,g=d[3];var e=/^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;d=e.exec(g);if(d==null){return f}while(d!=null){var c=d[1].startsWith("[")?d[2].gsub("\\\\]","]"):d[1];b=b[c];if(null==b||""==d[3]){break}g=g.substring("["==d[3]?d[1].length:d[0].length);d=e.exec(g)}return f+String.interpret(b)})}});Template.Pattern=/(^|.|\r|\n)(#\{(.*?)\})/;var $break={};var Enumerable={each:function(c,b){var a=0;c=c.bind(b);try{this._each(function(e){c(e,a++)})}catch(d){if(d!=$break){throw d}}return this},eachSlice:function(d,c,b){c=c?c.bind(b):Prototype.K;var a=-d,e=[],f=this.toArray();while((a+=d)<f.length){e.push(f.slice(a,a+d))}return e.collect(c,b)},all:function(c,b){c=c?c.bind(b):Prototype.K;var a=true;this.each(function(e,d){a=a&&!!c(e,d);if(!a){throw $break}});return a},any:function(c,b){c=c?c.bind(b):Prototype.K;var a=false;this.each(function(e,d){if(a=!!c(e,d)){throw $break}});return a},collect:function(c,b){c=c?c.bind(b):Prototype.K;var a=[];this.each(function(e,d){a.push(c(e,d))});return a},detect:function(c,b){c=c.bind(b);var a;this.each(function(e,d){if(c(e,d)){a=e;throw $break}});return a},findAll:function(c,b){c=c.bind(b);var a=[];this.each(function(e,d){if(c(e,d)){a.push(e)}});return a},grep:function(d,c,b){c=c?c.bind(b):Prototype.K;var a=[];if(Object.isString(d)){d=new RegExp(d)}this.each(function(f,e){if(d.match(f)){a.push(c(f,e))}});return a},include:function(a){if(Object.isFunction(this.indexOf)){if(this.indexOf(a)!=-1){return true}}var b=false;this.each(function(c){if(c==a){b=true;throw $break}});return b},inGroupsOf:function(b,a){a=Object.isUndefined(a)?null:a;return this.eachSlice(b,function(c){while(c.length<b){c.push(a)}return c})},inject:function(a,c,b){c=c.bind(b);this.each(function(e,d){a=c(a,e,d)});return a},invoke:function(b){var a=$A(arguments).slice(1);return this.map(function(c){return c[b].apply(c,a)})},max:function(c,b){c=c?c.bind(b):Prototype.K;var a;this.each(function(e,d){e=c(e,d);if(a==null||e>=a){a=e}});return a},min:function(c,b){c=c?c.bind(b):Prototype.K;var a;this.each(function(e,d){e=c(e,d);if(a==null||e<a){a=e}});return a},partition:function(d,b){d=d?d.bind(b):Prototype.K;var c=[],a=[];this.each(function(f,e){(d(f,e)?c:a).push(f)});return[c,a]},pluck:function(b){var a=[];this.each(function(c){a.push(c[b])});return a},reject:function(c,b){c=c.bind(b);var a=[];this.each(function(e,d){if(!c(e,d)){a.push(e)}});return a},sortBy:function(b,a){b=b.bind(a);return this.map(function(d,c){return{value:d,criteria:b(d,c)}}).sort(function(f,e){var d=f.criteria,c=e.criteria;return d<c?-1:d>c?1:0}).pluck("value")},toArray:function(){return this.map()},zip:function(){var b=Prototype.K,a=$A(arguments);if(Object.isFunction(a.last())){b=a.pop()}var c=[this].concat(a).map($A);return this.map(function(e,d){return b(c.pluck(d))})},size:function(){return this.toArray().length},inspect:function(){return"#<Enumerable:"+this.toArray().inspect()+">"}};Object.extend(Enumerable,{map:Enumerable.collect,find:Enumerable.detect,select:Enumerable.findAll,filter:Enumerable.findAll,member:Enumerable.include,entries:Enumerable.toArray,every:Enumerable.all,some:Enumerable.any});function $A(c){if(!c){return[]}if(c.toArray){return c.toArray()}var b=c.length||0,a=new Array(b);while(b--){a[b]=c[b]}return a}if(Prototype.Browser.WebKit){$A=function(c){if(!c){return[]}if(!(Object.isFunction(c)&&c=="[object NodeList]")&&c.toArray){return c.toArray()}var b=c.length||0,a=new Array(b);while(b--){a[b]=c[b]}return a}}Array.from=$A;Object.extend(Array.prototype,Enumerable);if(!Array.prototype._reverse){Array.prototype._reverse=Array.prototype.reverse}Object.extend(Array.prototype,{_each:function(b){for(var a=0,c=this.length;a<c;a++){b(this[a])}},clear:function(){this.length=0;return this},first:function(){return this[0]},last:function(){return this[this.length-1]},compact:function(){return this.select(function(a){return a!=null})},flatten:function(){return this.inject([],function(b,a){return b.concat(Object.isArray(a)?a.flatten():[a])})},without:function(){var a=$A(arguments);return this.select(function(b){return !a.include(b)})},reverse:function(a){return(a!==false?this:this.toArray())._reverse()},reduce:function(){return this.length>1?this:this[0]},uniq:function(a){return this.inject([],function(d,c,b){if(0==b||(a?d.last()!=c:!d.include(c))){d.push(c)}return d})},intersect:function(a){return this.uniq().findAll(function(b){return a.detect(function(c){return b===c})})},clone:function(){return[].concat(this)},size:function(){return this.length},inspect:function(){return"["+this.map(Object.inspect).join(", ")+"]"},toJSON:function(){var a=[];this.each(function(b){var c=Object.toJSON(b);if(!Object.isUndefined(c)){a.push(c)}});return"["+a.join(", ")+"]"}});if(Object.isFunction(Array.prototype.forEach)){Array.prototype._each=Array.prototype.forEach}if(!Array.prototype.indexOf){Array.prototype.indexOf=function(c,a){a||(a=0);var b=this.length;if(a<0){a=b+a}for(;a<b;a++){if(this[a]===c){return a}}return -1}}if(!Array.prototype.lastIndexOf){Array.prototype.lastIndexOf=function(b,a){a=isNaN(a)?this.length:(a<0?this.length+a:a)+1;var c=this.slice(0,a).reverse().indexOf(b);return(c<0)?c:a-c-1}}Array.prototype.toArray=Array.prototype.clone;function $w(a){if(!Object.isString(a)){return[]}a=a.strip();return a?a.split(/\s+/):[]}if(Prototype.Browser.Opera){Array.prototype.concat=function(){var e=[];for(var b=0,c=this.length;b<c;b++){e.push(this[b])}for(var b=0,c=arguments.length;b<c;b++){if(Object.isArray(arguments[b])){for(var a=0,d=arguments[b].length;a<d;a++){e.push(arguments[b][a])}}else{e.push(arguments[b])}}return e}}Object.extend(Number.prototype,{toColorPart:function(){return this.toPaddedString(2,16)},succ:function(){return this+1},times:function(a){$R(0,this,true).each(a);return this},toPaddedString:function(c,b){var a=this.toString(b||10);return"0".times(c-a.length)+a},toJSON:function(){return isFinite(this)?this.toString():"null"}});$w("abs round ceil floor").each(function(a){Number.prototype[a]=Math[a].methodize()});function $H(a){return new Hash(a)}var Hash=Class.create(Enumerable,(function(){function a(b,c){if(Object.isUndefined(c)){return b}return b+"="+encodeURIComponent(String.interpret(c))}return{initialize:function(b){this._object=Object.isHash(b)?b.toObject():Object.clone(b)},_each:function(c){for(var b in this._object){var d=this._object[b],e=[b,d];e.key=b;e.value=d;c(e)}},set:function(b,c){return this._object[b]=c},get:function(b){return this._object[b]},unset:function(b){var c=this._object[b];delete this._object[b];return c},toObject:function(){return Object.clone(this._object)},keys:function(){return this.pluck("key")},values:function(){return this.pluck("value")},index:function(c){var b=this.detect(function(d){return d.value===c});return b&&b.key},merge:function(b){return this.clone().update(b)},update:function(b){return new Hash(b).inject(this,function(c,d){c.set(d.key,d.value);return c})},toQueryString:function(){return this.map(function(d){var c=encodeURIComponent(d.key),b=d.value;if(b&&typeof b=="object"){if(Object.isArray(b)){return b.map(a.curry(c)).join("&")}}return a(c,b)}).join("&")},inspect:function(){return"#<Hash:{"+this.map(function(b){return b.map(Object.inspect).join(": ")}).join(", ")+"}>"},toJSON:function(){return Object.toJSON(this.toObject())},clone:function(){return new Hash(this)}}})());Hash.prototype.toTemplateReplacements=Hash.prototype.toObject;Hash.from=$H;var ObjectRange=Class.create(Enumerable,{initialize:function(c,a,b){this.start=c;this.end=a;this.exclusive=b},_each:function(a){var b=this.start;while(this.include(b)){a(b);b=b.succ()}},include:function(a){if(a<this.start){return false}if(this.exclusive){return a<this.end}return a<=this.end}});var $R=function(c,a,b){return new ObjectRange(c,a,b)};var Ajax={getTransport:function(){return Try.these(function(){return new XMLHttpRequest()},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Microsoft.XMLHTTP")})||false},activeRequestCount:0};Ajax.Responders={responders:[],_each:function(a){this.responders._each(a)},register:function(a){if(!this.include(a)){this.responders.push(a)}},unregister:function(a){this.responders=this.responders.without(a)},dispatch:function(d,b,c,a){this.each(function(f){if(Object.isFunction(f[d])){try{f[d].apply(f,[b,c,a])}catch(g){}}})}};Object.extend(Ajax.Responders,Enumerable);Ajax.Responders.register({onCreate:function(){Ajax.activeRequestCount++},onComplete:function(){Ajax.activeRequestCount--}});Ajax.Base=Class.create({initialize:function(a){this.options={method:"post",asynchronous:true,contentType:"application/x-www-form-urlencoded",encoding:"UTF-8",parameters:"",evalJSON:true,evalJS:true};Object.extend(this.options,a||{});this.options.method=this.options.method.toLowerCase();if(Object.isString(this.options.parameters)){this.options.parameters=this.options.parameters.toQueryParams()}else{if(Object.isHash(this.options.parameters)){this.options.parameters=this.options.parameters.toObject()}}}});Ajax.Request=Class.create(Ajax.Base,{_complete:false,initialize:function($super,b,a){$super(a);this.transport=Ajax.getTransport();this.request(b)},request:function(b){this.url=b;this.method=this.options.method;var d=Object.clone(this.options.parameters);if(!["get","post"].include(this.method)){d._method=this.method;this.method="post"}this.parameters=d;if(d=Object.toQueryString(d)){if(this.method=="get"){this.url+=(this.url.include("?")?"&":"?")+d}else{if(/Konqueror|Safari|KHTML/.test(navigator.userAgent)){d+="&_="}}}try{var a=new Ajax.Response(this);if(this.options.onCreate){this.options.onCreate(a)}Ajax.Responders.dispatch("onCreate",this,a);this.transport.open(this.method.toUpperCase(),this.url,this.options.asynchronous);if(this.options.asynchronous){this.respondToReadyState.bind(this).defer(1)}this.transport.onreadystatechange=this.onStateChange.bind(this);this.setRequestHeaders();this.body=this.method=="post"?(this.options.postBody||d):null;this.transport.send(this.body);if(!this.options.asynchronous&&this.transport.overrideMimeType){this.onStateChange()}}catch(c){this.dispatchException(c)}},onStateChange:function(){var a=this.transport.readyState;if(a>1&&!((a==4)&&this._complete)){this.respondToReadyState(this.transport.readyState)}},setRequestHeaders:function(){var e={"X-Requested-With":"XMLHttpRequest","X-Prototype-Version":Prototype.Version,Accept:"text/javascript, text/html, application/xml, text/xml, */*"};if(this.method=="post"){e["Content-type"]=this.options.contentType+(this.options.encoding?"; charset="+this.options.encoding:"");if(this.transport.overrideMimeType&&(navigator.userAgent.match(/Gecko\/(\d{4})/)||[0,2005])[1]<2005){e.Connection="close"}}if(typeof this.options.requestHeaders=="object"){var c=this.options.requestHeaders;if(Object.isFunction(c.push)){for(var b=0,d=c.length;b<d;b+=2){e[c[b]]=c[b+1]}}else{$H(c).each(function(f){e[f.key]=f.value})}}for(var a in e){this.transport.setRequestHeader(a,e[a])}},success:function(){var a=this.getStatus();return !a||(a>=200&&a<300)},getStatus:function(){try{return this.transport.status||0}catch(a){return 0}},respondToReadyState:function(a){var c=Ajax.Request.Events[a],b=new Ajax.Response(this);if(c=="Complete"){try{this._complete=true;(this.options["on"+b.status]||this.options["on"+(this.success()?"Success":"Failure")]||Prototype.emptyFunction)(b,b.headerJSON)}catch(d){this.dispatchException(d)}var f=b.getHeader("Content-type");if(this.options.evalJS=="force"||(this.options.evalJS&&this.isSameOrigin()&&f&&f.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i))){this.evalResponse()}}try{(this.options["on"+c]||Prototype.emptyFunction)(b,b.headerJSON);Ajax.Responders.dispatch("on"+c,this,b,b.headerJSON)}catch(d){this.dispatchException(d)}if(c=="Complete"){this.transport.onreadystatechange=Prototype.emptyFunction}},isSameOrigin:function(){var a=this.url.match(/^\s*https?:\/\/[^\/]*/);return !a||(a[0]=="#{protocol}//#{domain}#{port}".interpolate({protocol:location.protocol,domain:document.domain,port:location.port?":"+location.port:""}))},getHeader:function(a){try{return this.transport.getResponseHeader(a)||null}catch(b){return null}},evalResponse:function(){try{return eval((this.transport.responseText||"").unfilterJSON())}catch(e){this.dispatchException(e)}},dispatchException:function(a){(this.options.onException||Prototype.emptyFunction)(this,a);Ajax.Responders.dispatch("onException",this,a)}});Ajax.Request.Events=["Uninitialized","Loading","Loaded","Interactive","Complete"];Ajax.Response=Class.create({initialize:function(c){this.request=c;var d=this.transport=c.transport,a=this.readyState=d.readyState;if((a>2&&!Prototype.Browser.IE)||a==4){this.status=this.getStatus();this.statusText=this.getStatusText();this.responseText=String.interpret(d.responseText);this.headerJSON=this._getHeaderJSON()}if(a==4){var b=d.responseXML;this.responseXML=Object.isUndefined(b)?null:b;this.responseJSON=this._getResponseJSON()}},status:0,statusText:"",getStatus:Ajax.Request.prototype.getStatus,getStatusText:function(){try{return this.transport.statusText||""}catch(a){return""}},getHeader:Ajax.Request.prototype.getHeader,getAllHeaders:function(){try{return this.getAllResponseHeaders()}catch(a){return null}},getResponseHeader:function(a){return this.transport.getResponseHeader(a)},getAllResponseHeaders:function(){return this.transport.getAllResponseHeaders()},_getHeaderJSON:function(){var a=this.getHeader("X-JSON");if(!a){return null}a=decodeURIComponent(escape(a));try{return a.evalJSON(this.request.options.sanitizeJSON||!this.request.isSameOrigin())}catch(b){this.request.dispatchException(b)}},_getResponseJSON:function(){var a=this.request.options;if(!a.evalJSON||(a.evalJSON!="force"&&!(this.getHeader("Content-type")||"").include("application/json"))||this.responseText.blank()){return null}try{return this.responseText.evalJSON(a.sanitizeJSON||!this.request.isSameOrigin())}catch(b){this.request.dispatchException(b)}}});Ajax.Updater=Class.create(Ajax.Request,{initialize:function($super,a,c,b){this.container={success:(a.success||a),failure:(a.failure||(a.success?null:a))};b=Object.clone(b);var d=b.onComplete;b.onComplete=(function(e,f){this.updateContent(e.responseText);if(Object.isFunction(d)){d(e,f)}}).bind(this);$super(c,b)},updateContent:function(d){var c=this.container[this.success()?"success":"failure"],a=this.options;if(!a.evalScripts){d=d.stripScripts()}if(c=$(c)){if(a.insertion){if(Object.isString(a.insertion)){var b={};b[a.insertion]=d;c.insert(b)}else{a.insertion(c,d)}}else{c.update(d)}}}});Ajax.PeriodicalUpdater=Class.create(Ajax.Base,{initialize:function($super,a,c,b){$super(b);this.onComplete=this.options.onComplete;this.frequency=(this.options.frequency||2);this.decay=(this.options.decay||1);this.updater={};this.container=a;this.url=c;this.start()},start:function(){this.options.onComplete=this.updateComplete.bind(this);this.onTimerEvent()},stop:function(){this.updater.options.onComplete=undefined;clearTimeout(this.timer);(this.onComplete||Prototype.emptyFunction).apply(this,arguments)},updateComplete:function(a){if(this.options.decay){this.decay=(a.responseText==this.lastText?this.decay*this.options.decay:1);this.lastText=a.responseText}this.timer=this.onTimerEvent.bind(this).delay(this.decay*this.frequency)},onTimerEvent:function(){this.updater=new Ajax.Updater(this.container,this.url,this.options)}});function $(b){if(arguments.length>1){for(var a=0,d=[],c=arguments.length;a<c;a++){d.push($(arguments[a]))}return d}if(Object.isString(b)){b=document.getElementById(b)}return Element.extend(b)}if(Prototype.BrowserFeatures.XPath){document._getElementsByXPath=function(f,a){var c=[];var e=document.evaluate(f,$(a)||document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);for(var b=0,d=e.snapshotLength;b<d;b++){c.push(Element.extend(e.snapshotItem(b)))}return c}}if(!window.Node){var Node={}}if(!Node.ELEMENT_NODE){Object.extend(Node,{ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12})}(function(){var a=this.Element;this.Element=function(d,c){c=c||{};d=d.toLowerCase();var b=Element.cache;if(Prototype.Browser.IE&&c.name){d="<"+d+' name="'+c.name+'">';delete c.name;return Element.writeAttribute(document.createElement(d),c)}if(!b[d]){b[d]=Element.extend(document.createElement(d))}return Element.writeAttribute(b[d].cloneNode(false),c)};Object.extend(this.Element,a||{})}).call(window);Element.cache={};Element.Methods={visible:function(a){return $(a).style.display!="none"},toggle:function(a){a=$(a);Element[Element.visible(a)?"hide":"show"](a);return a},hide:function(a){$(a).style.display="none";return a},show:function(a){$(a).style.display="";return a},remove:function(a){a=$(a);a.parentNode.removeChild(a);return a},update:function(a,b){a=$(a);if(b&&b.toElement){b=b.toElement()}if(Object.isElement(b)){return a.update().insert(b)}b=Object.toHTML(b);a.innerHTML=b.stripScripts();b.evalScripts.bind(b).defer();return a},replace:function(b,c){b=$(b);if(c&&c.toElement){c=c.toElement()}else{if(!Object.isElement(c)){c=Object.toHTML(c);var a=b.ownerDocument.createRange();a.selectNode(b);c.evalScripts.bind(c).defer();c=a.createContextualFragment(c.stripScripts())}}b.parentNode.replaceChild(c,b);return b},insert:function(c,e){c=$(c);if(Object.isString(e)||Object.isNumber(e)||Object.isElement(e)||(e&&(e.toElement||e.toHTML))){e={bottom:e}}var d,f,b,g;for(var a in e){d=e[a];a=a.toLowerCase();f=Element._insertionTranslations[a];if(d&&d.toElement){d=d.toElement()}if(Object.isElement(d)){f(c,d);continue}d=Object.toHTML(d);b=((a=="before"||a=="after")?c.parentNode:c).tagName.toUpperCase();g=Element._getContentFromAnonymousElement(b,d.stripScripts());if(a=="top"||a=="after"){g.reverse()}g.each(f.curry(c));d.evalScripts.bind(d).defer()}return c},wrap:function(b,c,a){b=$(b);if(Object.isElement(c)){$(c).writeAttribute(a||{})}else{if(Object.isString(c)){c=new Element(c,a)}else{c=new Element("div",c)}}if(b.parentNode){b.parentNode.replaceChild(c,b)}c.appendChild(b);return c},inspect:function(b){b=$(b);var a="<"+b.tagName.toLowerCase();$H({id:"id",className:"class"}).each(function(f){var e=f.first(),c=f.last();var d=(b[e]||"").toString();if(d){a+=" "+c+"="+d.inspect(true)}});return a+">"},recursivelyCollect:function(a,c){a=$(a);var b=[];while(a=a[c]){if(a.nodeType==1){b.push(Element.extend(a))}}return b},ancestors:function(a){return $(a).recursivelyCollect("parentNode")},descendants:function(a){return $(a).select("*")},firstDescendant:function(a){a=$(a).firstChild;while(a&&a.nodeType!=1){a=a.nextSibling}return $(a)},immediateDescendants:function(a){if(!(a=$(a).firstChild)){return[]}while(a&&a.nodeType!=1){a=a.nextSibling}if(a){return[a].concat($(a).nextSiblings())}return[]},previousSiblings:function(a){return $(a).recursivelyCollect("previousSibling")},nextSiblings:function(a){return $(a).recursivelyCollect("nextSibling")},siblings:function(a){a=$(a);return a.previousSiblings().reverse().concat(a.nextSiblings())},match:function(b,a){if(Object.isString(a)){a=new Selector(a)}return a.match($(b))},up:function(b,d,a){b=$(b);if(arguments.length==1){return $(b.parentNode)}var c=b.ancestors();return Object.isNumber(d)?c[d]:Selector.findElement(c,d,a)},down:function(b,c,a){b=$(b);if(arguments.length==1){return b.firstDescendant()}return Object.isNumber(c)?b.descendants()[c]:b.select(c)[a||0]},previous:function(b,d,a){b=$(b);if(arguments.length==1){return $(Selector.handlers.previousElementSibling(b))}var c=b.previousSiblings();return Object.isNumber(d)?c[d]:Selector.findElement(c,d,a)},next:function(c,d,b){c=$(c);if(arguments.length==1){return $(Selector.handlers.nextElementSibling(c))}var a=c.nextSiblings();return Object.isNumber(d)?a[d]:Selector.findElement(a,d,b)},select:function(){var a=$A(arguments),b=$(a.shift());return Selector.findChildElements(b,a)},adjacent:function(){var a=$A(arguments),b=$(a.shift());return Selector.findChildElements(b.parentNode,a).without(b)},identify:function(b){b=$(b);var c=b.readAttribute("id"),a=arguments.callee;if(c){return c}do{c="anonymous_element_"+a.counter++}while($(c));b.writeAttribute("id",c);return c},readAttribute:function(c,a){c=$(c);if(Prototype.Browser.IE){var b=Element._attributeTranslations.read;if(b.values[a]){return b.values[a](c,a)}if(b.names[a]){a=b.names[a]}if(a.include(":")){return(!c.attributes||!c.attributes[a])?null:c.attributes[a].value}}return c.getAttribute(a)},writeAttribute:function(e,c,f){e=$(e);var b={},d=Element._attributeTranslations.write;if(typeof c=="object"){b=c}else{b[c]=Object.isUndefined(f)?true:f}for(var a in b){c=d.names[a]||a;f=b[a];if(d.values[a]){c=d.values[a](e,f)}if(f===false||f===null){e.removeAttribute(c)}else{if(f===true){e.setAttribute(c,c)}else{e.setAttribute(c,f)}}}return e},getHeight:function(a){return $(a).getDimensions().height},getWidth:function(a){return $(a).getDimensions().width},classNames:function(a){return new Element.ClassNames(a)},hasClassName:function(a,b){if(!(a=$(a))){return}var c=a.className;return(c.length>0&&(c==b||new RegExp("(^|\\s)"+b+"(\\s|$)").test(c)))},addClassName:function(a,b){if(!(a=$(a))){return}if(!a.hasClassName(b)){a.className+=(a.className?" ":"")+b}return a},removeClassName:function(a,b){if(!(a=$(a))){return}a.className=a.className.replace(new RegExp("(^|\\s+)"+b+"(\\s+|$)")," ").strip();return a},toggleClassName:function(a,b){if(!(a=$(a))){return}return a[a.hasClassName(b)?"removeClassName":"addClassName"](b)},cleanWhitespace:function(b){b=$(b);var c=b.firstChild;while(c){var a=c.nextSibling;if(c.nodeType==3&&!/\S/.test(c.nodeValue)){b.removeChild(c)}c=a}return b},empty:function(a){return $(a).innerHTML.blank()},descendantOf:function(f,d){f=$(f),d=$(d);var h=d;if(f.compareDocumentPosition){return(f.compareDocumentPosition(d)&8)===8}if(f.sourceIndex&&!Prototype.Browser.Opera){var g=f.sourceIndex,c=d.sourceIndex,b=d.nextSibling;if(!b){do{d=d.parentNode}while(!(b=d.nextSibling)&&d.parentNode)}if(b&&b.sourceIndex){return(g>c&&g<b.sourceIndex)}}while(f=f.parentNode){if(f==h){return true}}return false},scrollTo:function(a){a=$(a);var b=a.cumulativeOffset();window.scrollTo(b[0],b[1]);return a},getStyle:function(b,c){b=$(b);c=c=="float"?"cssFloat":c.camelize();var d=b.style[c];if(!d){var a=document.defaultView.getComputedStyle(b,null);d=a?a[c]:null}if(c=="opacity"){return d?parseFloat(d):1}return d=="auto"?null:d},getOpacity:function(a){return $(a).getStyle("opacity")},setStyle:function(b,c){b=$(b);var e=b.style,a;if(Object.isString(c)){b.style.cssText+=";"+c;return c.include("opacity")?b.setOpacity(c.match(/opacity:\s*(\d?\.?\d*)/)[1]):b}for(var d in c){if(d=="opacity"){b.setOpacity(c[d])}else{e[(d=="float"||d=="cssFloat")?(Object.isUndefined(e.styleFloat)?"cssFloat":"styleFloat"):d]=c[d]}}return b},setOpacity:function(a,b){a=$(a);a.style.opacity=(b==1||b==="")?"":(b<0.00001)?0:b;return a},getDimensions:function(c){c=$(c);var g=$(c).getStyle("display");if(g!="none"&&g!=null){return{width:c.offsetWidth,height:c.offsetHeight}}var b=c.style;var f=b.visibility;var d=b.position;var a=b.display;b.visibility="hidden";b.position="absolute";b.display="block";var h=c.clientWidth;var e=c.clientHeight;b.display=a;b.position=d;b.visibility=f;return{width:h,height:e}},makePositioned:function(a){a=$(a);var b=Element.getStyle(a,"position");if(b=="static"||!b){a._madePositioned=true;a.style.position="relative";if(window.opera){a.style.top=0;a.style.left=0}}return a},undoPositioned:function(a){a=$(a);if(a._madePositioned){a._madePositioned=undefined;a.style.position=a.style.top=a.style.left=a.style.bottom=a.style.right=""}return a},makeClipping:function(a){a=$(a);if(a._overflow){return a}a._overflow=Element.getStyle(a,"overflow")||"auto";if(a._overflow!=="hidden"){a.style.overflow="hidden"}return a},undoClipping:function(a){a=$(a);if(!a._overflow){return a}a.style.overflow=a._overflow=="auto"?"":a._overflow;a._overflow=null;return a},cumulativeOffset:function(b){var a=0,c=0;do{a+=b.offsetTop||0;c+=b.offsetLeft||0;b=b.offsetParent}while(b);return Element._returnOffset(c,a)},positionedOffset:function(b){var a=0,d=0;do{a+=b.offsetTop||0;d+=b.offsetLeft||0;b=b.offsetParent;if(b){if(b.tagName=="BODY"){break}var c=Element.getStyle(b,"position");if(c!=="static"){break}}}while(b);return Element._returnOffset(d,a)},absolutize:function(b){b=$(b);if(b.getStyle("position")=="absolute"){return}var d=b.positionedOffset();var f=d[1];var e=d[0];var c=b.clientWidth;var a=b.clientHeight;b._originalLeft=e-parseFloat(b.style.left||0);b._originalTop=f-parseFloat(b.style.top||0);b._originalWidth=b.style.width;b._originalHeight=b.style.height;b.style.position="absolute";b.style.top=f+"px";b.style.left=e+"px";b.style.width=c+"px";b.style.height=a+"px";return b},relativize:function(a){a=$(a);if(a.getStyle("position")=="relative"){return}a.style.position="relative";var c=parseFloat(a.style.top||0)-(a._originalTop||0);var b=parseFloat(a.style.left||0)-(a._originalLeft||0);a.style.top=c+"px";a.style.left=b+"px";a.style.height=a._originalHeight;a.style.width=a._originalWidth;return a},cumulativeScrollOffset:function(b){var a=0,c=0;do{a+=b.scrollTop||0;c+=b.scrollLeft||0;b=b.parentNode}while(b);return Element._returnOffset(c,a)},getOffsetParent:function(a){if(a.offsetParent){return $(a.offsetParent)}if(a==document.body){return $(a)}while((a=a.parentNode)&&a!=document.body){if(Element.getStyle(a,"position")!="static"){return $(a)}}return $(document.body)},viewportOffset:function(d){var a=0,c=0;var b=d;do{a+=b.offsetTop||0;c+=b.offsetLeft||0;if(b.offsetParent==document.body&&Element.getStyle(b,"position")=="absolute"){break}}while(b=b.offsetParent);b=d;do{if(!Prototype.Browser.Opera||b.tagName=="BODY"){a-=b.scrollTop||0;c-=b.scrollLeft||0}}while(b=b.parentNode);return Element._returnOffset(c,a)},clonePosition:function(b,d){var a=Object.extend({setLeft:true,setTop:true,setWidth:true,setHeight:true,offsetTop:0,offsetLeft:0},arguments[2]||{});d=$(d);var e=d.viewportOffset();b=$(b);var f=[0,0];var c=null;if(Element.getStyle(b,"position")=="absolute"){c=b.getOffsetParent();f=c.viewportOffset()}if(c==document.body){f[0]-=document.body.offsetLeft;f[1]-=document.body.offsetTop}if(a.setLeft){b.style.left=(e[0]-f[0]+a.offsetLeft)+"px"}if(a.setTop){b.style.top=(e[1]-f[1]+a.offsetTop)+"px"}if(a.setWidth){b.style.width=d.offsetWidth+"px"}if(a.setHeight){b.style.height=d.offsetHeight+"px"}return b}};Element.Methods.identify.counter=1;Object.extend(Element.Methods,{getElementsBySelector:Element.Methods.select,childElements:Element.Methods.immediateDescendants});Element._attributeTranslations={write:{names:{className:"class",htmlFor:"for"},values:{}}};if(Prototype.Browser.Opera){Element.Methods.getStyle=Element.Methods.getStyle.wrap(function(d,b,c){switch(c){case"left":case"top":case"right":case"bottom":if(d(b,"position")==="static"){return null}case"height":case"width":if(!Element.visible(b)){return null}var e=parseInt(d(b,c),10);if(e!==b["offset"+c.capitalize()]){return e+"px"}var a;if(c==="height"){a=["border-top-width","padding-top","padding-bottom","border-bottom-width"]}else{a=["border-left-width","padding-left","padding-right","border-right-width"]}return a.inject(e,function(f,g){var h=d(b,g);return h===null?f:f-parseInt(h,10)})+"px";default:return d(b,c)}});Element.Methods.readAttribute=Element.Methods.readAttribute.wrap(function(c,a,b){if(b==="title"){return a.title}return c(a,b)})}else{if(Prototype.Browser.IE){Element.Methods.getOffsetParent=Element.Methods.getOffsetParent.wrap(function(c,b){b=$(b);var a=b.getStyle("position");if(a!=="static"){return c(b)}b.setStyle({position:"relative"});var d=c(b);b.setStyle({position:a});return d});$w("positionedOffset viewportOffset").each(function(a){Element.Methods[a]=Element.Methods[a].wrap(function(e,c){c=$(c);var b=c.getStyle("position");if(b!=="static"){return e(c)}var d=c.getOffsetParent();if(d&&d.getStyle("position")==="fixed"){d.setStyle({zoom:1})}c.setStyle({position:"relative"});var f=e(c);c.setStyle({position:b});return f})});Element.Methods.getStyle=function(a,b){a=$(a);b=(b=="float"||b=="cssFloat")?"styleFloat":b.camelize();var c=a.style[b];if(!c&&a.currentStyle){c=a.currentStyle[b]}if(b=="opacity"){if(c=(a.getStyle("filter")||"").match(/alpha\(opacity=(.*)\)/)){if(c[1]){return parseFloat(c[1])/100}}return 1}if(c=="auto"){if((b=="width"||b=="height")&&(a.getStyle("display")!="none")){return a["offset"+b.capitalize()]+"px"}return null}return c};Element.Methods.setOpacity=function(b,e){function f(g){return g.replace(/alpha\([^\)]*\)/gi,"")}b=$(b);var a=b.currentStyle;if((a&&!a.hasLayout)||(!a&&b.style.zoom=="normal")){b.style.zoom=1}var d=b.getStyle("filter"),c=b.style;if(e==1||e===""){(d=f(d))?c.filter=d:c.removeAttribute("filter");return b}else{if(e<0.00001){e=0}}c.filter=f(d)+"alpha(opacity="+(e*100)+")";return b};Element._attributeTranslations={read:{names:{"class":"className","for":"htmlFor"},values:{_getAttr:function(a,b){return a.getAttribute(b,2)},_getAttrNode:function(a,c){var b=a.getAttributeNode(c);return b?b.value:""},_getEv:function(a,b){b=a.getAttribute(b);return b?b.toString().slice(23,-2):null},_flag:function(a,b){return $(a).hasAttribute(b)?b:null},style:function(a){return a.style.cssText.toLowerCase()},title:function(a){return a.title}}}};Element._attributeTranslations.write={names:Object.extend({cellpadding:"cellPadding",cellspacing:"cellSpacing"},Element._attributeTranslations.read.names),values:{checked:function(a,b){a.checked=!!b},style:function(a,b){a.style.cssText=b?b:""}}};Element._attributeTranslations.has={};$w("colSpan rowSpan vAlign dateTime accessKey tabIndex encType maxLength readOnly longDesc").each(function(a){Element._attributeTranslations.write.names[a.toLowerCase()]=a;Element._attributeTranslations.has[a.toLowerCase()]=a});(function(a){Object.extend(a,{href:a._getAttr,src:a._getAttr,type:a._getAttr,action:a._getAttrNode,disabled:a._flag,checked:a._flag,readonly:a._flag,multiple:a._flag,onload:a._getEv,onunload:a._getEv,onclick:a._getEv,ondblclick:a._getEv,onmousedown:a._getEv,onmouseup:a._getEv,onmouseover:a._getEv,onmousemove:a._getEv,onmouseout:a._getEv,onfocus:a._getEv,onblur:a._getEv,onkeypress:a._getEv,onkeydown:a._getEv,onkeyup:a._getEv,onsubmit:a._getEv,onreset:a._getEv,onselect:a._getEv,onchange:a._getEv})})(Element._attributeTranslations.read.values)}else{if(Prototype.Browser.Gecko&&/rv:1\.8\.0/.test(navigator.userAgent)){Element.Methods.setOpacity=function(a,b){a=$(a);a.style.opacity=(b==1)?0.999999:(b==="")?"":(b<0.00001)?0:b;return a}}else{if(Prototype.Browser.WebKit){Element.Methods.setOpacity=function(a,b){a=$(a);a.style.opacity=(b==1||b==="")?"":(b<0.00001)?0:b;if(b==1){if(a.tagName=="IMG"&&a.width){a.width++;a.width--}else{try{var d=document.createTextNode(" ");a.appendChild(d);a.removeChild(d)}catch(c){}}}return a};Element.Methods.cumulativeOffset=function(b){var a=0,c=0;do{a+=b.offsetTop||0;c+=b.offsetLeft||0;if(b.offsetParent==document.body){if(Element.getStyle(b,"position")=="absolute"){break}}b=b.offsetParent}while(b);return Element._returnOffset(c,a)}}}}}if(Prototype.Browser.IE||Prototype.Browser.Opera){Element.Methods.update=function(b,c){b=$(b);if(c&&c.toElement){c=c.toElement()}if(Object.isElement(c)){return b.update().insert(c)}c=Object.toHTML(c);var a=b.tagName.toUpperCase();if(a in Element._insertionTranslations.tags){$A(b.childNodes).each(function(d){b.removeChild(d)});Element._getContentFromAnonymousElement(a,c.stripScripts()).each(function(d){b.appendChild(d)})}else{b.innerHTML=c.stripScripts()}c.evalScripts.bind(c).defer();return b}}if("outerHTML" in document.createElement("div")){Element.Methods.replace=function(c,e){c=$(c);if(e&&e.toElement){e=e.toElement()}if(Object.isElement(e)){c.parentNode.replaceChild(e,c);return c}e=Object.toHTML(e);var d=c.parentNode,b=d.tagName.toUpperCase();if(Element._insertionTranslations.tags[b]){var f=c.next();var a=Element._getContentFromAnonymousElement(b,e.stripScripts());d.removeChild(c);if(f){a.each(function(g){d.insertBefore(g,f)})}else{a.each(function(g){d.appendChild(g)})}}else{c.outerHTML=e.stripScripts()}e.evalScripts.bind(e).defer();return c}}Element._returnOffset=function(b,c){var a=[b,c];a.left=b;a.top=c;return a};Element._getContentFromAnonymousElement=function(c,b){var d=new Element("div"),a=Element._insertionTranslations.tags[c];if(a){d.innerHTML=a[0]+b+a[1];a[2].times(function(){d=d.firstChild})}else{d.innerHTML=b}return $A(d.childNodes)};Element._insertionTranslations={before:function(a,b){a.parentNode.insertBefore(b,a)},top:function(a,b){a.insertBefore(b,a.firstChild)},bottom:function(a,b){a.appendChild(b)},after:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},tags:{TABLE:["<table>","</table>",1],TBODY:["<table><tbody>","</tbody></table>",2],TR:["<table><tbody><tr>","</tr></tbody></table>",3],TD:["<table><tbody><tr><td>","</td></tr></tbody></table>",4],SELECT:["<select>","</select>",1]}};(function(){Object.extend(this.tags,{THEAD:this.tags.TBODY,TFOOT:this.tags.TBODY,TH:this.tags.TD})}).call(Element._insertionTranslations);Element.Methods.Simulated={hasAttribute:function(a,c){c=Element._attributeTranslations.has[c]||c;var b=$(a).getAttributeNode(c);return b&&b.specified}};Element.Methods.ByTag={};Object.extend(Element,Element.Methods);if(!Prototype.BrowserFeatures.ElementExtensions&&document.createElement("div").__proto__){window.HTMLElement={};window.HTMLElement.prototype=document.createElement("div").__proto__;Prototype.BrowserFeatures.ElementExtensions=true}Element.extend=(function(){if(Prototype.BrowserFeatures.SpecificElementExtensions){return Prototype.K}var a={},b=Element.Methods.ByTag;var c=Object.extend(function(f){if(!f||f._extendedByPrototype||f.nodeType!=1||f==window){return f}var d=Object.clone(a),e=f.tagName,h,g;if(b[e]){Object.extend(d,b[e])}for(h in d){g=d[h];if(Object.isFunction(g)&&!(h in f)){f[h]=g.methodize()}}f._extendedByPrototype=Prototype.emptyFunction;return f},{refresh:function(){if(!Prototype.BrowserFeatures.ElementExtensions){Object.extend(a,Element.Methods);Object.extend(a,Element.Methods.Simulated)}}});c.refresh();return c})();Element.hasAttribute=function(a,b){if(a.hasAttribute){return a.hasAttribute(b)}return Element.Methods.Simulated.hasAttribute(a,b)};Element.addMethods=function(c){var h=Prototype.BrowserFeatures,d=Element.Methods.ByTag;if(!c){Object.extend(Form,Form.Methods);Object.extend(Form.Element,Form.Element.Methods);Object.extend(Element.Methods.ByTag,{FORM:Object.clone(Form.Methods),INPUT:Object.clone(Form.Element.Methods),SELECT:Object.clone(Form.Element.Methods),TEXTAREA:Object.clone(Form.Element.Methods)})}if(arguments.length==2){var b=c;c=arguments[1]}if(!b){Object.extend(Element.Methods,c||{})}else{if(Object.isArray(b)){b.each(g)}else{g(b)}}function g(j){j=j.toUpperCase();if(!Element.Methods.ByTag[j]){Element.Methods.ByTag[j]={}}Object.extend(Element.Methods.ByTag[j],c)}function a(l,k,j){j=j||false;for(var n in l){var m=l[n];if(!Object.isFunction(m)){continue}if(!j||!(n in k)){k[n]=m.methodize()}}}function e(l){var j;var k={OPTGROUP:"OptGroup",TEXTAREA:"TextArea",P:"Paragraph",FIELDSET:"FieldSet",UL:"UList",OL:"OList",DL:"DList",DIR:"Directory",H1:"Heading",H2:"Heading",H3:"Heading",H4:"Heading",H5:"Heading",H6:"Heading",Q:"Quote",INS:"Mod",DEL:"Mod",A:"Anchor",IMG:"Image",CAPTION:"TableCaption",COL:"TableCol",COLGROUP:"TableCol",THEAD:"TableSection",TFOOT:"TableSection",TBODY:"TableSection",TR:"TableRow",TH:"TableCell",TD:"TableCell",FRAMESET:"FrameSet",IFRAME:"IFrame"};if(k[l]){j="HTML"+k[l]+"Element"}if(window[j]){return window[j]}j="HTML"+l+"Element";if(window[j]){return window[j]}j="HTML"+l.capitalize()+"Element";if(window[j]){return window[j]}window[j]={};window[j].prototype=document.createElement(l).__proto__;return window[j]}if(h.ElementExtensions){a(Element.Methods,HTMLElement.prototype);a(Element.Methods.Simulated,HTMLElement.prototype,true)}if(h.SpecificElementExtensions){for(var i in Element.Methods.ByTag){var f=e(i);if(Object.isUndefined(f)){continue}a(d[i],f.prototype)}}Object.extend(Element,Element.Methods);delete Element.ByTag;if(Element.extend.refresh){Element.extend.refresh()}Element.cache={}};document.viewport={getDimensions:function(){var a={};var b=Prototype.Browser;$w("width height").each(function(e){var c=e.capitalize();a[e]=(b.WebKit&&!document.evaluate)?self["inner"+c]:(b.Opera)?document.body["client"+c]:document.documentElement["client"+c]});return a},getWidth:function(){return this.getDimensions().width},getHeight:function(){return this.getDimensions().height},getScrollOffsets:function(){return Element._returnOffset(window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft,window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop)}};var Selector=Class.create({initialize:function(a){this.expression=a.strip();this.compileMatcher()},shouldUseXPath:function(){if(!Prototype.BrowserFeatures.XPath){return false}var a=this.expression;if(Prototype.Browser.WebKit&&(a.include("-of-type")||a.include(":empty"))){return false}if((/(\[[\w-]*?:|:checked)/).test(this.expression)){return false}return true},compileMatcher:function(){if(this.shouldUseXPath()){return this.compileXPathMatcher()}var e=this.expression,ps=Selector.patterns,h=Selector.handlers,c=Selector.criteria,le,p,m;if(Selector._cache[e]){this.matcher=Selector._cache[e];return}this.matcher=["this.matcher = function(root) {","var r = root, h = Selector.handlers, c = false, n;"];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i in ps){p=ps[i];if(m=e.match(p)){this.matcher.push(Object.isFunction(c[i])?c[i](m):new Template(c[i]).evaluate(m));e=e.replace(m[0],"");break}}}this.matcher.push("return h.unique(n);\n}");eval(this.matcher.join("\n"));Selector._cache[this.expression]=this.matcher},compileXPathMatcher:function(){var f=this.expression,g=Selector.patterns,b=Selector.xpath,d,a;if(Selector._cache[f]){this.xpath=Selector._cache[f];return}this.matcher=[".//*"];while(f&&d!=f&&(/\S/).test(f)){d=f;for(var c in g){if(a=f.match(g[c])){this.matcher.push(Object.isFunction(b[c])?b[c](a):new Template(b[c]).evaluate(a));f=f.replace(a[0],"");break}}}this.xpath=this.matcher.join("");Selector._cache[this.expression]=this.xpath},findElements:function(a){a=a||document;if(this.xpath){return document._getElementsByXPath(this.xpath,a)}return this.matcher(a)},match:function(j){this.tokens=[];var o=this.expression,a=Selector.patterns,f=Selector.assertions;var b,d,g;while(o&&b!==o&&(/\S/).test(o)){b=o;for(var k in a){d=a[k];if(g=o.match(d)){if(f[k]){this.tokens.push([k,Object.clone(g)]);o=o.replace(g[0],"")}else{return this.findElements(document).include(j)}}}}var n=true,c,l;for(var k=0,h;h=this.tokens[k];k++){c=h[0],l=h[1];if(!Selector.assertions[c](j,l)){n=false;break}}return n},toString:function(){return this.expression},inspect:function(){return"#<Selector:"+this.expression.inspect()+">"}});Object.extend(Selector,{_cache:{},xpath:{descendant:"//*",child:"/*",adjacent:"/following-sibling::*[1]",laterSibling:"/following-sibling::*",tagName:function(a){if(a[1]=="*"){return""}return"[local-name()='"+a[1].toLowerCase()+"' or local-name()='"+a[1].toUpperCase()+"']"},className:"[contains(concat(' ', @class, ' '), ' #{1} ')]",id:"[@id='#{1}']",attrPresence:function(a){a[1]=a[1].toLowerCase();return new Template("[@#{1}]").evaluate(a)},attr:function(a){a[1]=a[1].toLowerCase();a[3]=a[5]||a[6];return new Template(Selector.xpath.operators[a[2]]).evaluate(a)},pseudo:function(a){var b=Selector.xpath.pseudos[a[1]];if(!b){return""}if(Object.isFunction(b)){return b(a)}return new Template(Selector.xpath.pseudos[a[1]]).evaluate(a)},operators:{"=":"[@#{1}='#{3}']","!=":"[@#{1}!='#{3}']","^=":"[starts-with(@#{1}, '#{3}')]","$=":"[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']","*=":"[contains(@#{1}, '#{3}')]","~=":"[contains(concat(' ', @#{1}, ' '), ' #{3} ')]","|=":"[contains(concat('-', @#{1}, '-'), '-#{3}-')]"},pseudos:{"first-child":"[not(preceding-sibling::*)]","last-child":"[not(following-sibling::*)]","only-child":"[not(preceding-sibling::* or following-sibling::*)]",empty:"[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",checked:"[@checked]",disabled:"[@disabled]",enabled:"[not(@disabled)]",not:function(b){var j=b[6],h=Selector.patterns,a=Selector.xpath,f,c;var g=[];while(j&&f!=j&&(/\S/).test(j)){f=j;for(var d in h){if(b=j.match(h[d])){c=Object.isFunction(a[d])?a[d](b):new Template(a[d]).evaluate(b);g.push("("+c.substring(1,c.length-1)+")");j=j.replace(b[0],"");break}}}return"[not("+g.join(" and ")+")]"},"nth-child":function(a){return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ",a)},"nth-last-child":function(a){return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ",a)},"nth-of-type":function(a){return Selector.xpath.pseudos.nth("position() ",a)},"nth-last-of-type":function(a){return Selector.xpath.pseudos.nth("(last() + 1 - position()) ",a)},"first-of-type":function(a){a[6]="1";return Selector.xpath.pseudos["nth-of-type"](a)},"last-of-type":function(a){a[6]="1";return Selector.xpath.pseudos["nth-last-of-type"](a)},"only-of-type":function(a){var b=Selector.xpath.pseudos;return b["first-of-type"](a)+b["last-of-type"](a)},nth:function(g,e){var h,i=e[6],d;if(i=="even"){i="2n+0"}if(i=="odd"){i="2n+1"}if(h=i.match(/^(\d+)$/)){return"["+g+"= "+h[1]+"]"}if(h=i.match(/^(-?\d*)?n(([+-])(\d+))?/)){if(h[1]=="-"){h[1]=-1}var f=h[1]?Number(h[1]):1;var c=h[2]?Number(h[2]):0;d="[((#{fragment} - #{b}) mod #{a} = 0) and ((#{fragment} - #{b}) div #{a} >= 0)]";return new Template(d).evaluate({fragment:g,a:f,b:c})}}}},criteria:{tagName:'n = h.tagName(n, r, "#{1}", c);      c = false;',className:'n = h.className(n, r, "#{1}", c);    c = false;',id:'n = h.id(n, r, "#{1}", c);           c = false;',attrPresence:'n = h.attrPresence(n, r, "#{1}", c); c = false;',attr:function(a){a[3]=(a[5]||a[6]);return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(a)},pseudo:function(a){if(a[6]){a[6]=a[6].replace(/"/g,'\\"')}return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(a)},descendant:'c = "descendant";',child:'c = "child";',adjacent:'c = "adjacent";',laterSibling:'c = "laterSibling";'},patterns:{laterSibling:/^\s*~\s*/,child:/^\s*>\s*/,adjacent:/^\s*\+\s*/,descendant:/^\s/,tagName:/^\s*(\*|[\w\-]+)(\b|$)?/,id:/^#([\w\-\*]+)(\b|$)/,className:/^\.([\w\-\*]+)(\b|$)/,pseudo:/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,attrPresence:/^\[([\w]+)\]/,attr:/\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/},assertions:{tagName:function(a,b){return b[1].toUpperCase()==a.tagName.toUpperCase()},className:function(a,b){return Element.hasClassName(a,b[1])},id:function(a,b){return a.id===b[1]},attrPresence:function(a,b){return Element.hasAttribute(a,b[1])},attr:function(b,c){var a=Element.readAttribute(b,c[1]);return a&&Selector.operators[c[2]](a,c[5]||c[6])}},handlers:{concat:function(d,c){for(var e=0,f;f=c[e];e++){d.push(f)}return d},mark:function(a){var d=Prototype.emptyFunction;for(var b=0,c;c=a[b];b++){c._countedByPrototype=d}return a},unmark:function(a){for(var b=0,c;c=a[b];b++){c._countedByPrototype=undefined}return a},index:function(a,d,g){a._countedByPrototype=Prototype.emptyFunction;if(d){for(var b=a.childNodes,e=b.length-1,c=1;e>=0;e--){var f=b[e];if(f.nodeType==1&&(!g||f._countedByPrototype)){f.nodeIndex=c++}}}else{for(var e=0,c=1,b=a.childNodes;f=b[e];e++){if(f.nodeType==1&&(!g||f._countedByPrototype)){f.nodeIndex=c++}}}},unique:function(b){if(b.length==0){return b}var d=[],e;for(var c=0,a=b.length;c<a;c++){if(!(e=b[c])._countedByPrototype){e._countedByPrototype=Prototype.emptyFunction;d.push(Element.extend(e))}}return Selector.handlers.unmark(d)},descendant:function(a){var d=Selector.handlers;for(var c=0,b=[],e;e=a[c];c++){d.concat(b,e.getElementsByTagName("*"))}return b},child:function(a){var e=Selector.handlers;for(var d=0,c=[],f;f=a[d];d++){for(var b=0,g;g=f.childNodes[b];b++){if(g.nodeType==1&&g.tagName!="!"){c.push(g)}}}return c},adjacent:function(a){for(var c=0,b=[],e;e=a[c];c++){var d=this.nextElementSibling(e);if(d){b.push(d)}}return b},laterSibling:function(a){var d=Selector.handlers;for(var c=0,b=[],e;e=a[c];c++){d.concat(b,Element.nextSiblings(e))}return b},nextElementSibling:function(a){while(a=a.nextSibling){if(a.nodeType==1){return a}}return null},previousElementSibling:function(a){while(a=a.previousSibling){if(a.nodeType==1){return a}}return null},tagName:function(a,j,c,b){var k=c.toUpperCase();var e=[],g=Selector.handlers;if(a){if(b){if(b=="descendant"){for(var f=0,d;d=a[f];f++){g.concat(e,d.getElementsByTagName(c))}return e}else{a=this[b](a)}if(c=="*"){return a}}for(var f=0,d;d=a[f];f++){if(d.tagName.toUpperCase()===k){e.push(d)}}return e}else{return j.getElementsByTagName(c)}},id:function(b,a,j,f){var g=$(j),d=Selector.handlers;if(!g){return[]}if(!b&&a==document){return[g]}if(b){if(f){if(f=="child"){for(var c=0,e;e=b[c];c++){if(g.parentNode==e){return[g]}}}else{if(f=="descendant"){for(var c=0,e;e=b[c];c++){if(Element.descendantOf(g,e)){return[g]}}}else{if(f=="adjacent"){for(var c=0,e;e=b[c];c++){if(Selector.handlers.previousElementSibling(g)==e){return[g]}}}else{b=d[f](b)}}}}for(var c=0,e;e=b[c];c++){if(e==g){return[g]}}return[]}return(g&&Element.descendantOf(g,a))?[g]:[]},className:function(b,a,c,d){if(b&&d){b=this[d](b)}return Selector.handlers.byClassName(b,a,c)},byClassName:function(c,b,f){if(!c){c=Selector.handlers.descendant([b])}var h=" "+f+" ";for(var e=0,d=[],g,a;g=c[e];e++){a=g.className;if(a.length==0){continue}if(a==f||(" "+a+" ").include(h)){d.push(g)}}return d},attrPresence:function(c,b,a,g){if(!c){c=b.getElementsByTagName("*")}if(c&&g){c=this[g](c)}var e=[];for(var d=0,f;f=c[d];d++){if(Element.hasAttribute(f,a)){e.push(f)}}return e},attr:function(a,j,h,k,c,b){if(!a){a=j.getElementsByTagName("*")}if(a&&b){a=this[b](a)}var l=Selector.operators[c],f=[];for(var e=0,d;d=a[e];e++){var g=Element.readAttribute(d,h);if(g===null){continue}if(l(g,k)){f.push(d)}}return f},pseudo:function(b,c,e,a,d){if(b&&d){b=this[d](b)}if(!b){b=a.getElementsByTagName("*")}return Selector.pseudos[c](b,e,a)}},pseudos:{"first-child":function(b,f,a){for(var d=0,c=[],e;e=b[d];d++){if(Selector.handlers.previousElementSibling(e)){continue}c.push(e)}return c},"last-child":function(b,f,a){for(var d=0,c=[],e;e=b[d];d++){if(Selector.handlers.nextElementSibling(e)){continue}c.push(e)}return c},"only-child":function(b,g,a){var e=Selector.handlers;for(var d=0,c=[],f;f=b[d];d++){if(!e.previousElementSibling(f)&&!e.nextElementSibling(f)){c.push(f)}}return c},"nth-child":function(b,c,a){return Selector.pseudos.nth(b,c,a)},"nth-last-child":function(b,c,a){return Selector.pseudos.nth(b,c,a,true)},"nth-of-type":function(b,c,a){return Selector.pseudos.nth(b,c,a,false,true)},"nth-last-of-type":function(b,c,a){return Selector.pseudos.nth(b,c,a,true,true)},"first-of-type":function(b,c,a){return Selector.pseudos.nth(b,"1",a,false,true)},"last-of-type":function(b,c,a){return Selector.pseudos.nth(b,"1",a,true,true)},"only-of-type":function(b,d,a){var c=Selector.pseudos;return c["last-of-type"](c["first-of-type"](b,d,a),d,a)},getIndices:function(d,c,e){if(d==0){return c>0?[c]:[]}return $R(1,e).inject([],function(a,b){if(0==(b-c)%d&&(b-c)/d>=0){a.push(b)}return a})},nth:function(c,s,u,r,e){if(c.length==0){return[]}if(s=="even"){s="2n+0"}if(s=="odd"){s="2n+1"}var q=Selector.handlers,p=[],d=[],g;q.mark(c);for(var o=0,f;f=c[o];o++){if(!f.parentNode._countedByPrototype){q.index(f.parentNode,r,e);d.push(f.parentNode)}}if(s.match(/^\d+$/)){s=Number(s);for(var o=0,f;f=c[o];o++){if(f.nodeIndex==s){p.push(f)}}}else{if(g=s.match(/^(-?\d*)?n(([+-])(\d+))?/)){if(g[1]=="-"){g[1]=-1}var v=g[1]?Number(g[1]):1;var t=g[2]?Number(g[2]):0;var w=Selector.pseudos.getIndices(v,t,c.length);for(var o=0,f,k=w.length;f=c[o];o++){for(var n=0;n<k;n++){if(f.nodeIndex==w[n]){p.push(f)}}}}}q.unmark(c);q.unmark(d);return p},empty:function(b,f,a){for(var d=0,c=[],e;e=b[d];d++){if(e.tagName=="!"||(e.firstChild&&!e.innerHTML.match(/^\s*$/))){continue}c.push(e)}return c},not:function(a,d,k){var g=Selector.handlers,l,c;var j=new Selector(d).findElements(k);g.mark(j);for(var f=0,e=[],b;b=a[f];f++){if(!b._countedByPrototype){e.push(b)}}g.unmark(j);return e},enabled:function(b,f,a){for(var d=0,c=[],e;e=b[d];d++){if(!e.disabled){c.push(e)}}return c},disabled:function(b,f,a){for(var d=0,c=[],e;e=b[d];d++){if(e.disabled){c.push(e)}}return c},checked:function(b,f,a){for(var d=0,c=[],e;e=b[d];d++){if(e.checked){c.push(e)}}return c}},operators:{"=":function(b,a){return b==a},"!=":function(b,a){return b!=a},"^=":function(b,a){return b.startsWith(a)},"$=":function(b,a){return b.endsWith(a)},"*=":function(b,a){return b.include(a)},"~=":function(b,a){return(" "+b+" ").include(" "+a+" ")},"|=":function(b,a){return("-"+b.toUpperCase()+"-").include("-"+a.toUpperCase()+"-")}},split:function(b){var a=[];b.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/,function(c){a.push(c[1].strip())});return a},matchElements:function(f,g){var e=$$(g),d=Selector.handlers;d.mark(e);for(var c=0,b=[],a;a=f[c];c++){if(a._countedByPrototype){b.push(a)}}d.unmark(e);return b},findElement:function(b,c,a){if(Object.isNumber(c)){a=c;c=false}return Selector.matchElements(b,c||"*")[a||0]},findChildElements:function(e,g){g=Selector.split(g.join(","));var d=[],f=Selector.handlers;for(var c=0,b=g.length,a;c<b;c++){a=new Selector(g[c].strip());f.concat(d,a.findElements(e))}return(b>1)?f.unique(d):d}});if(Prototype.Browser.IE){Object.extend(Selector.handlers,{concat:function(d,c){for(var e=0,f;f=c[e];e++){if(f.tagName!=="!"){d.push(f)}}return d},unmark:function(a){for(var b=0,c;c=a[b];b++){c.removeAttribute("_countedByPrototype")}return a}})}function $$(){return Selector.findChildElements(document,$A(arguments))}var Form={reset:function(a){$(a).reset();return a},serializeElements:function(g,b){if(typeof b!="object"){b={hash:!!b}}else{if(Object.isUndefined(b.hash)){b.hash=true}}var c,f,a=false,e=b.submit;var d=g.inject({},function(h,i){if(!i.disabled&&i.name){c=i.name;f=$(i).getValue();if(f!=null&&(i.type!="submit"||(!a&&e!==false&&(!e||c==e)&&(a=true)))){if(c in h){if(!Object.isArray(h[c])){h[c]=[h[c]]}h[c].push(f)}else{h[c]=f}}}return h});return b.hash?d:Object.toQueryString(d)}};Form.Methods={serialize:function(b,a){return Form.serializeElements(Form.getElements(b),a)},getElements:function(a){return $A($(a).getElementsByTagName("*")).inject([],function(b,c){if(Form.Element.Serializers[c.tagName.toLowerCase()]){b.push(Element.extend(c))}return b})},getInputs:function(g,c,d){g=$(g);var a=g.getElementsByTagName("input");if(!c&&!d){return $A(a).map(Element.extend)}for(var e=0,h=[],f=a.length;e<f;e++){var b=a[e];if((c&&b.type!=c)||(d&&b.name!=d)){continue}h.push(Element.extend(b))}return h},disable:function(a){a=$(a);Form.getElements(a).invoke("disable");return a},enable:function(a){a=$(a);Form.getElements(a).invoke("enable");return a},findFirstElement:function(b){var c=$(b).getElements().findAll(function(d){return"hidden"!=d.type&&!d.disabled});var a=c.findAll(function(d){return d.hasAttribute("tabIndex")&&d.tabIndex>=0}).sortBy(function(d){return d.tabIndex}).first();return a?a:c.find(function(d){return["input","select","textarea"].include(d.tagName.toLowerCase())})},focusFirstElement:function(a){a=$(a);a.findFirstElement().activate();return a},request:function(b,a){b=$(b),a=Object.clone(a||{});var d=a.parameters,c=b.readAttribute("action")||"";if(c.blank()){c=window.location.href}a.parameters=b.serialize(true);if(d){if(Object.isString(d)){d=d.toQueryParams()}Object.extend(a.parameters,d)}if(b.hasAttribute("method")&&!a.method){a.method=b.method}return new Ajax.Request(c,a)}};Form.Element={focus:function(a){$(a).focus();return a},select:function(a){$(a).select();return a}};Form.Element.Methods={serialize:function(a){a=$(a);if(!a.disabled&&a.name){var b=a.getValue();if(b!=undefined){var c={};c[a.name]=b;return Object.toQueryString(c)}}return""},getValue:function(a){a=$(a);var b=a.tagName.toLowerCase();return Form.Element.Serializers[b](a)},setValue:function(a,b){a=$(a);var c=a.tagName.toLowerCase();Form.Element.Serializers[c](a,b);return a},clear:function(a){$(a).value="";return a},present:function(a){return $(a).value!=""},activate:function(a){a=$(a);try{a.focus();if(a.select&&(a.tagName.toLowerCase()!="input"||!["button","reset","submit"].include(a.type))){a.select()}}catch(b){}return a},disable:function(a){a=$(a);a.blur();a.disabled=true;return a},enable:function(a){a=$(a);a.disabled=false;return a}};var Field=Form.Element;var $F=Form.Element.Methods.getValue;Form.Element.Serializers={input:function(a,b){switch(a.type.toLowerCase()){case"checkbox":case"radio":return Form.Element.Serializers.inputSelector(a,b);default:return Form.Element.Serializers.textarea(a,b)}},inputSelector:function(a,b){if(Object.isUndefined(b)){return a.checked?a.value:null}else{a.checked=!!b}},textarea:function(a,b){if(Object.isUndefined(b)){return a.value}else{a.value=b}},select:function(d,a){if(Object.isUndefined(a)){return this[d.type=="select-one"?"selectOne":"selectMany"](d)}else{var c,f,g=!Object.isArray(a);for(var b=0,e=d.length;b<e;b++){c=d.options[b];f=this.optionValue(c);if(g){if(f==a){c.selected=true;return}}else{c.selected=a.include(f)}}}},selectOne:function(b){var a=b.selectedIndex;return a>=0?this.optionValue(b.options[a]):null},selectMany:function(d){var a,e=d.length;if(!e){return null}for(var c=0,a=[];c<e;c++){var b=d.options[c];if(b.selected){a.push(this.optionValue(b))}}return a},optionValue:function(a){return Element.extend(a).hasAttribute("value")?a.value:a.text}};Abstract.TimedObserver=Class.create(PeriodicalExecuter,{initialize:function($super,a,b,c){$super(c,b);this.element=$(a);this.lastValue=this.getValue()},execute:function(){var a=this.getValue();if(Object.isString(this.lastValue)&&Object.isString(a)?this.lastValue!=a:String(this.lastValue)!=String(a)){this.callback(this.element,a);this.lastValue=a}}});Form.Element.Observer=Class.create(Abstract.TimedObserver,{getValue:function(){return Form.Element.getValue(this.element)}});Form.Observer=Class.create(Abstract.TimedObserver,{getValue:function(){return Form.serialize(this.element)}});Abstract.EventObserver=Class.create({initialize:function(a,b){this.element=$(a);this.callback=b;this.lastValue=this.getValue();if(this.element.tagName.toLowerCase()=="form"){this.registerFormCallbacks()}else{this.registerCallback(this.element)}},onElementEvent:function(){var a=this.getValue();if(this.lastValue!=a){this.callback(this.element,a);this.lastValue=a}},registerFormCallbacks:function(){Form.getElements(this.element).each(this.registerCallback,this)},registerCallback:function(a){if(a.type){switch(a.type.toLowerCase()){case"checkbox":case"radio":Event.observe(a,"click",this.onElementEvent.bind(this));break;default:Event.observe(a,"change",this.onElementEvent.bind(this));break}}}});Form.Element.EventObserver=Class.create(Abstract.EventObserver,{getValue:function(){return Form.Element.getValue(this.element)}});Form.EventObserver=Class.create(Abstract.EventObserver,{getValue:function(){return Form.serialize(this.element)}});if(!window.Event){var Event={}}Object.extend(Event,{KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ESC:27,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_DELETE:46,KEY_HOME:36,KEY_END:35,KEY_PAGEUP:33,KEY_PAGEDOWN:34,KEY_INSERT:45,cache:{},relatedTarget:function(b){var a;switch(b.type){case"mouseover":a=b.fromElement;break;case"mouseout":a=b.toElement;break;default:return null}return Element.extend(a)}});Event.Methods=(function(){var a;if(Prototype.Browser.IE){var b={0:1,1:4,2:2};a=function(d,c){return d.button==b[c]}}else{if(Prototype.Browser.WebKit){a=function(d,c){switch(c){case 0:return d.which==1&&!d.metaKey;case 1:return d.which==1&&d.metaKey;default:return false}}}else{a=function(d,c){return d.which?(d.which===c+1):(d.button===c)}}}return{isLeftClick:function(c){return a(c,0)},isMiddleClick:function(c){return a(c,1)},isRightClick:function(c){return a(c,2)},element:function(d){var c=Event.extend(d).target;return Element.extend(c.nodeType==Node.TEXT_NODE?c.parentNode:c)},findElement:function(d,f){var c=Event.element(d);if(!f){return c}var e=[c].concat(c.ancestors());return Selector.findElement(e,f,0)},pointer:function(c){return{x:c.pageX||(c.clientX+(document.documentElement.scrollLeft||document.body.scrollLeft)),y:c.pageY||(c.clientY+(document.documentElement.scrollTop||document.body.scrollTop))}},pointerX:function(c){return Event.pointer(c).x},pointerY:function(c){return Event.pointer(c).y},stop:function(c){Event.extend(c);c.preventDefault();c.stopPropagation();c.stopped=true}}})();Event.extend=(function(){var a=Object.keys(Event.Methods).inject({},function(b,c){b[c]=Event.Methods[c].methodize();return b});if(Prototype.Browser.IE){Object.extend(a,{stopPropagation:function(){this.cancelBubble=true},preventDefault:function(){this.returnValue=false},inspect:function(){return"[object Event]"}});return function(b){if(!b){return false}if(b._extendedByPrototype){return b}b._extendedByPrototype=Prototype.emptyFunction;var c=Event.pointer(b);Object.extend(b,{target:b.srcElement,relatedTarget:Event.relatedTarget(b),pageX:c.x,pageY:c.y});return Object.extend(b,a)}}else{Event.prototype=Event.prototype||document.createEvent("HTMLEvents").__proto__;Object.extend(Event.prototype,a);return Prototype.K}})();Object.extend(Event,(function(){var b=Event.cache;function c(j){if(j._prototypeEventID){return j._prototypeEventID[0]}arguments.callee.id=arguments.callee.id||1;return j._prototypeEventID=[++arguments.callee.id]}function g(j){if(j&&j.include(":")){return"dataavailable"}return j}function a(j){return b[j]=b[j]||{}}function f(l,j){var k=a(l);return k[j]=k[j]||[]}function h(k,j,l){var o=c(k);var n=f(o,j);if(n.pluck("handler").include(l)){return false}var m=function(p){if(!Event||!Event.extend||(p.eventName&&p.eventName!=j)){return false}Event.extend(p);l.call(k,p)};m.handler=l;n.push(m);return m}function i(m,j,k){var l=f(m,j);return l.find(function(n){return n.handler==k})}function d(m,j,k){var l=a(m);if(!l[j]){return false}l[j]=l[j].without(i(m,j,k))}function e(){for(var k in b){for(var j in b[k]){b[k][j]=null}}}if(window.attachEvent){window.attachEvent("onunload",e)}return{observe:function(l,j,m){l=$(l);var k=g(j);var n=h(l,j,m);if(!n){return l}if(l.addEventListener){l.addEventListener(k,n,false)}else{l.attachEvent("on"+k,n)}return l},stopObserving:function(l,j,m){l=$(l);var o=c(l),k=g(j);if(!m&&j){f(o,j).each(function(p){l.stopObserving(j,p.handler)});return l}else{if(!j){Object.keys(a(o)).each(function(p){l.stopObserving(p)});return l}}var n=i(o,j,m);if(!n){return l}if(l.removeEventListener){l.removeEventListener(k,n,false)}else{l.detachEvent("on"+k,n)}d(o,j,m);return l},fire:function(l,k,j){l=$(l);if(l==document&&document.createEvent&&!l.dispatchEvent){l=document.documentElement}var m;if(document.createEvent){m=document.createEvent("HTMLEvents");m.initEvent("dataavailable",true,true)}else{m=document.createEventObject();m.eventType="ondataavailable"}m.eventName=k;m.memo=j||{};if(document.createEvent){l.dispatchEvent(m)}else{l.fireEvent(m.eventType,m)}return Event.extend(m)}}})());Object.extend(Event,Event.Methods);Element.addMethods({fire:Event.fire,observe:Event.observe,stopObserving:Event.stopObserving});Object.extend(document,{fire:Element.Methods.fire.methodize(),observe:Element.Methods.observe.methodize(),stopObserving:Element.Methods.stopObserving.methodize(),loaded:false});(function(){var b;function a(){if(document.loaded){return}if(b){window.clearInterval(b)}document.fire("dom:loaded");document.loaded=true}if(document.addEventListener){if(Prototype.Browser.WebKit){b=window.setInterval(function(){if(/loaded|complete/.test(document.readyState)){a()}},0);Event.observe(window,"load",a)}else{document.addEventListener("DOMContentLoaded",a,false)}}else{document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");$("__onDOMContentLoaded").onreadystatechange=function(){if(this.readyState=="complete"){this.onreadystatechange=null;a()}}}})();Hash.toQueryString=Object.toQueryString;var Toggle={display:Element.toggle};Element.Methods.childOf=Element.Methods.descendantOf;var Insertion={Before:function(a,b){return Element.insert(a,{before:b})},Top:function(a,b){return Element.insert(a,{top:b})},Bottom:function(a,b){return Element.insert(a,{bottom:b})},After:function(a,b){return Element.insert(a,{after:b})}};var $continue=new Error('"throw $continue" is deprecated, use "return" instead');var Position={includeScrollOffsets:false,prepare:function(){this.deltaX=window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft||0;this.deltaY=window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop||0},within:function(b,a,c){if(this.includeScrollOffsets){return this.withinIncludingScrolloffsets(b,a,c)}this.xcomp=a;this.ycomp=c;this.offset=Element.cumulativeOffset(b);return(c>=this.offset[1]&&c<this.offset[1]+b.offsetHeight&&a>=this.offset[0]&&a<this.offset[0]+b.offsetWidth)},withinIncludingScrolloffsets:function(b,a,d){var c=Element.cumulativeScrollOffset(b);this.xcomp=a+c[0]-this.deltaX;this.ycomp=d+c[1]-this.deltaY;this.offset=Element.cumulativeOffset(b);return(this.ycomp>=this.offset[1]&&this.ycomp<this.offset[1]+b.offsetHeight&&this.xcomp>=this.offset[0]&&this.xcomp<this.offset[0]+b.offsetWidth)},overlap:function(b,a){if(!b){return 0}if(b=="vertical"){return((this.offset[1]+a.offsetHeight)-this.ycomp)/a.offsetHeight}if(b=="horizontal"){return((this.offset[0]+a.offsetWidth)-this.xcomp)/a.offsetWidth}},cumulativeOffset:Element.Methods.cumulativeOffset,positionedOffset:Element.Methods.positionedOffset,absolutize:function(a){Position.prepare();return Element.absolutize(a)},relativize:function(a){Position.prepare();return Element.relativize(a)},realOffset:Element.Methods.cumulativeScrollOffset,offsetParent:Element.Methods.getOffsetParent,page:Element.Methods.viewportOffset,clone:function(b,c,a){a=a||{};return Element.clonePosition(c,b,a)}};if(!document.getElementsByClassName){document.getElementsByClassName=function(b){function a(c){return c.blank()?null:"[contains(concat(' ', @class, ' '), ' "+c+" ')]"}b.getElementsByClassName=Prototype.BrowserFeatures.XPath?function(c,e){e=e.toString().strip();var d=/\s/.test(e)?$w(e).map(a).join(""):a(e);return d?document._getElementsByXPath(".//*"+d,c):[]}:function(e,f){f=f.toString().strip();var g=[],h=(/\s/.test(f)?$w(f):null);if(!h&&!f){return g}var c=$(e).getElementsByTagName("*");f=" "+f+" ";for(var d=0,k,j;k=c[d];d++){if(k.className&&(j=" "+k.className+" ")&&(j.include(f)||(h&&h.all(function(i){return !i.toString().blank()&&j.include(" "+i+" ")})))){g.push(Element.extend(k))}}return g};return function(d,c){return $(c||document.body).getElementsByClassName(d)}}(Element.Methods)}Element.ClassNames=Class.create();Element.ClassNames.prototype={initialize:function(a){this.element=$(a)},_each:function(a){this.element.className.split(/\s+/).select(function(b){return b.length>0})._each(a)},set:function(a){this.element.className=a},add:function(a){if(this.include(a)){return}this.set($A(this).concat(a).join(" "))},remove:function(a){if(!this.include(a)){return}this.set($A(this).without(a).join(" "))},toString:function(){return $A(this).join(" ")}};Object.extend(Element.ClassNames.prototype,Enumerable);Element.addMethods();
// Inspired by base2 and Prototype

(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
  // The base Class implementation (does nothing)
  this._Class = function(){};
  
  // Create a new Class that inherits from this class
  _Class.extend = function(prop) {
    var _super = this.prototype;
    
    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;
    
    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" && 
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;
            
            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];
            
            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);        
            this._super = tmp;
            
            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }
    
    // The dummy class constructor
    function _Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }
    
    // Populate our constructed prototype object
    _Class.prototype = prototype;
    
    // Enforce the constructor to be what we expect
    _Class.constructor = _Class;

    // And make this class extendable
    _Class.extend = arguments.callee;
    
    return _Class;
  };
})();

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed

(function(){
  var cache = {};
  
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(str) :
      
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
        
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
        
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
    
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();
/*
  Required:
    — jQuery
    — jQuery Easing plugin
    — John Resig Simple JavaScript Inheritance (object: "_Class")
*/

(function( $ ){
  
  this.classAnimate = _Class.extend({
    init: function( step, duration, easing, callback ){
    	this.opt = {
    		step: step,
    		complete: callback ? callback : function(){}
    	};
    	if( $.isFunction(easing) ){
    	  this.opt.complete = easing;
    	}

    	this.now = 0;
    	this.duration = duration;

    	this.easing = !$.isFunction(easing) ? easing : "swing";

    	this._init();
    },

  	_init: function(){
  		var self = this;
  		this.startTime = ( new Date() ).getTime();
  		this.timerId = setInterval(function(){
  			self.next();
  		}, 13);
  	},

  	next: function(){
  		this.prev = this.now;
  		var t = ( new Date() ).getTime();
  		this.step = t - this.startTime;

  		if( this.step > this.duration ){
  			this.step = this.duration;
  			this.exec();
  			clearInterval(this.timerId);
  			this.opt.complete.apply(this);

  			return;
  		}
		
  		this.exec();
  	},

  	exec: function(){
  		this.state = this.step / this.duration;
  		this.now = $.easing[this.easing](this.state, this.step, 0, 1, this.duration);
  		this.opt.step.apply(this, [this.now, this.prev]);
  	},

  	stop: function(){
  		clearInterval(this.timerId);
  	}
    
  })

})( jQuery );

/*
  Required:
    — jQuery
    — John Resig Simple JavaScript Inheritance (object: "_Class")
*/

(function( $ ){
  
  this.classDraggable = _Class.extend({

  	isDefault: {
  		drag: false,
  		clicked: false,
  		toclick: true,
  		mouseup: false
  	},

    // Main init method
  	init: function(){
  		if(arguments.length > 0){
  			this.ptr = $(arguments[0]);
  			this.outer = $(".draggable-outer");

  			this.is = {};
  			$.extend(this.is, this.isDefault);

  			var _offset = this.ptr.offset();
  			this.d = {
  				left: _offset.left,
  				top: _offset.top,
  				width: this.ptr.width(),
  				height: this.ptr.height()
  			};
			
  			this.oninit.apply(this, arguments);

  			this._events();
  		}
  	},


  	// Methods for re-init in child class
  	oninit: function(){},
  	events: function(){},
  	onmousedown: function(){
  		this.ptr.css({ position: "absolute" });
  	},
  	onmousemove: function(evt, x, y){
  		this.ptr.css({ left: x, top: y });
  	},
  	onmouseup: function(){},
  	

    // Basic events and method
  	_events: function(){
  		var oThis = this;

  		$(document)
  			.mousemove(function(evt){
  				if(oThis.is.drag){
  					oThis._mousemove(evt);
  					return false;
  				}
  			})
  			.mouseup(function(evt){
  				oThis._mouseup(evt);
  			})
  			.bind("dragstart", function(){
  				return false;
  			});

  		this.ptr
  			.mousedown(function(evt){
  				oThis._mousedown(evt);
  				return false;
  			})
  			.mouseup(function(evt){
  				oThis._mouseup(evt);
  			});
		
  		this.ptr.find("a")
  			.click(function(){
  				oThis.is.clicked = true;
  				if(!oThis.is.toclick){
  					oThis.is.toclick = true;
  					return false;
  				}
  			})
  			.mousedown(function(oEvt){
  				oThis._mousedown(oEvt);
  				return false;
  			})
  			.bind("dragstart", function(){
  				return false;
  			});

		
  		this.events();
  	},
  	_mousedown: function(evt){
  		this.is.drag = true;
  		this.is.clicked = false;
  		this.is.mouseup = false;
		
  		var _offset = this.ptr.offset();
  		this.cx = evt.pageX - _offset.left;
  		this.cy = evt.pageY - _offset.top;

  		$.extend(this.d, {
  			left: _offset.left,
  			top: _offset.top,
  			width: this.ptr.width(),
  			height: this.ptr.height()
  		});
		
  		if(this.outer && this.outer.get(0)){
  			this.outer.css({ height: Math.max(this.outer.height(), $(document.body).height()), overflow: "hidden" });
  		}
		
  		this.onmousedown(evt);
  	},
  	_mousemove: function(evt){
  		this.is.toclick = false;
  		this.onmousemove(evt, evt.pageX - this.cx, evt.pageY - this.cy);
  	},
  	_mouseup: function(evt){
  		var oThis = this;
  		if(this.is.drag){
  			this.is.drag = false;

  			if(this.outer && this.outer.get(0)){

  				if($.browser.mozilla) {
  					this.outer.css({ overflow: "hidden" });
  				} else {
  					this.outer.css({ overflow: "visible" });
  				}
				
  				if($.browser.msie && $.browser.version == '6.0') {
  					this.outer.css({ height: "100%" });
  				} else {
  					this.outer.css({ height: "auto" });
  				}	
  			}

  			this.onmouseup(evt);
  		}
  	}
  	
    
  })


})( jQuery );

/*
 * jQuery EasIng v1.1.2 - http://gsgd.co.uk/sandbox/jquery.easIng.php
 *
 * Uses the built In easIng capabilities added In jQuery 1.1
 * to offer multiple easIng options
 *
 * Copyright (c) 2007 George Smith
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// t: current time, b: begInnIng value, c: change In value, d: duration

jQuery.extend( jQuery.easing,
{
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

(function(b){function d(e,f){this.options=e;if(!e.cacheLength||e.cacheLength<1){this.options.cacheLength=1}this.persistent={};if(this.options.data){this.initPersistent(this.options.data)}this.flush()}d.prototype={flush:function(){this.data={};this.length=0},initPersistent:function(j){var e="",g={},l=[];for(var h=0;h<j.length;h++){l=j[h].strip();if(l.length>0){e=l.substring(0,1).toLowerCase();if(!g[e]){g[e]=[]}g[e].push(l)}}for(var f in g){this.addToPersistent(f,g[f])}},addToPersistent:function(f,e){if(!e||!f){return}this.persistent[f]=e},lookup:function(e){return this.merge(this.lookupPersistent(e),this.lookupTemp(e))},merge:function(g,f){var e=[];if(g){for(var h=0;h<g.length;h++){e[h]=g[h]}}if(f){for(h=0;h<f.length;h++){if(!e.include(f[h])){e[e.length]=f[h]}}}return e.length>0?e:null},lookupTemp:function(e){return this.lookupCache(e,this.data)},lookupPersistent:function(e){return this.lookupCache(e,this.persistent)},lookupCache:function(m,g){if(!m||!g){return null}if(g[m]){return g[m]}if(this.options.matchSubset){var l=[];for(var k=m.length-1;k>=this.options.minChars;k--){var f=m.substr(0,k);var n=g[f];if(n){for(var h=0;h<n.length;h++){var e=n[h];if(l.indexOf(e)==-1&&this.matchSubset(e,m)){l[l.length]=e}}}}l=l.uniq();if(l.length>0){g[m]=l;return l}}return null},matchSubset:function(g,f){if(!g){return false}if(!this.options.matchCase){g=g.toLowerCase()}var e=g.indexOf(f);if(e==-1){return false}return e===0||this.options.matchContains},store:function(f,e){if(!e||!f){return}if(!this.length){this.flush();this.length++}else{if(!this.data[f]){this.length++}}this.data[f]=e}};function a(e,g,f){var h=g.get(0);document.body.appendChild(h);this.results=b(h);this.timeout=null;this.input=e;this.results.hide();this.options=f;this.active=-1;if(typeof(this.options.width)=="string"){this.options.width=parseInt(this.options.width,10)}if(this.options.width>0){this.results.css("width",this.options.width)}}a.prototype={moveUp:function(){this.moveSelect(-1)},moveDown:function(){this.moveSelect(1)},moveSelect:function(g){var f=b("li",this.results);if(!f){return}this.active+=g;if(this.active<0){this.active=0}else{if(this.active>=f.size()){this.active=f.size()-1}}f.removeClass("selected");b(f[this.active]).addClass("selected");if(this.options.autoFill){var e=b(f[this.active]).get(0);this.input.autoFill(e.selectData||e.selectValue)}},hideNow:function(){if(this.timeout){clearTimeout(this.timeout)}if(this.results.is(":visible")){this.results.hide()}if(this.options.mustMatch){var e=this.input.value();if(e!=this.input.lastSelected){this.selectItem(null)}}},hide:function(){if(this.timeout){clearTimeout(this.timeout)}var e=this;this.timeout=setTimeout(function(){e.hideNow()},200)},selectCurrent:function(){var e=b("li.selected",this.results)[0];if(!e){var f=b("li",this.results);if(this.options.selectOnly){if(f.length==1){e=f[0]}}else{if(this.options.selectFirst){e=f[0]}}}if(e){this.selectItem(e);return true}else{return false}},show:function(){var f=(this.input.input.offset().top+this.input.input.get(0).offsetHeight);var e=this.input.input.offset().left;this.results.css({position:"absolute",width:(this.options.width+6)+"px",top:f+"px",left:e+"px",zIndex:999}).show().find("li:first").addClass("selected").end()},selectItem:function(e){if(!e){e=document.createElement("li");e.extra=[];e.selectValue=""}var f=b.trim(e.selectValue?e.selectValue:e.innerHTML);this.results.html("");this.input.trigger("valueselected",[f]);if(this.options.onItemSelect){setTimeout(function(){this.options.onItemSelect(e)},1)}},dataToDom:function(e){var h=document.createElement("ul");var g=e.length;var m=this;if((this.options.maxItemsToShow>0)&&(this.options.maxItemsToShow<g)){g=this.options.maxItemsToShow}for(var f=0;f<g;f++){var n=e[f];var k=document.createElement("li");if(this.options.formatItem){k.innerHTML=this.options.formatItem(n,f,g);k.selectValue=n}else{if(typeof(n)!="string"){k.innerHTML="";for(var j in n){if(n[j]){k.innerHTML+="<span>"+n[j]+"</span>"}}k.selectValue=n[this.options.select];k.selectData=n}else{k.innerHTML=n;k.selectValue=n}}h.appendChild(k)}var l=b(h).find("li");l.hover(function(){l.removeClass("selected");b(this).addClass("selected");m.active=l.indexOf(b(this).get(0))},function(){b(this).removeClass("selected")}).click(function(i){i.preventDefault();i.stopPropagation();m.selectItem(this)});return h},loadData:function(e){this.results.html("");if(b.browser.msie){}this.active=0;this.results.append(this.dataToDom(e))}};function c(f,h,g){this.input=b(f);this.input.get(0).autocompleter=h;this.input.attr("autocomplete","off");this.id="#"+this.input.attr("id");this.spinner=b(this.id+"_auto_complete_indicator");this.spinner.css("left",(parseInt(this.input.css("width"),10)-15)+"px");this.options=g;if(g.inputClass){this.input.addClass(g.inputClass)}this.hasFocus=false;this.lastKeyPressCode=null;var i=null;this.prev="";var e=this;this.input.keydown(function(j){this.lastKeyPressCode=j.keyCode;switch(j.keyCode){case 38:j.preventDefault();e.input.trigger("moveup");break;case 40:j.preventDefault();e.input.trigger("movedown");break;case 13:e.input.trigger("selectcurrent");j.preventDefault();return false;break;default:if(i){clearTimeout(i)}i=setTimeout(function(){e.change()},g.delay);break}}).focus(function(){e.hasFocus=true}).blur(function(){e.hasFocus=false;e.input.trigger("valuehide")})}c.prototype={change:function(){if(this.lastKeyPressCode==46||(this.lastKeyPressCode>8&&this.lastKeyPressCode<32)){return this.input.trigger("hide")}var e=this.value();if(e==this.prev){return}this.prev=e;if(e.length>=this.options.minChars){this.startLoad();this.input.trigger("valuechange",[e])}else{this.stopLoad();this.input.trigger("valuehide")}},startLoad:function(){this.input.addClass(this.options.loadingClass)},stopLoad:function(){this.input.removeClass(this.options.loadingClass);this.hideSpinner()},showSpinner:function(){this.spinner.show()},hideSpinner:function(){this.spinner.hide()},value:function(){var e=this.input.val().split(",").map(function(f){return f.strip()});return e.length>0?e[e.length-1]:""},setValue:function(e){var g=this.input.val().split(",").map(function(h){return h.strip()});var f=g.pop();g[g.length]=e;this.input.val(g.join(",")).trigger("valueSet",e)},currentStartPosition:function(){var e=this.input.val().lastIndexOf(",");return e>0?e+1:0},createSelection:function(i,f){var g=this.input.get(0);var h=this.currentStartPosition();i=h+i;f=h+f;if(g.createTextRange){var e=g.createTextRange();e.collapse(true);e.moveStart("character",i);e.moveEnd("character",f);e.select()}else{if(g.setSelectionRange){g.setSelectionRange(i,f)}else{if(g.selectionStart){g.selectionStart=i;g.selectionEnd=f}}}g.focus()},autoFill:function(e){var g=typeof(e)=="string"?e:e[this.options.select];if(this.lastKeyPressCode==8){return false}if(typeof(e)!="string"&&this.options.fieldPrefix){for(var f in e){b("#"+this.options.fieldPrefix+"_"+f).val(e[f])}}this.setValue(g);this.createSelection(this.prev.length,g.length)},receiveData:function(f,e){if(!this.hasFocus||!e.length){return false}if(this.options.autoFill&&(this.value().toLowerCase()==f.toLowerCase())){this.autoFill(e[0])}return true},trigger:function(e,f){this.input.trigger(e,f)}};b.autocomplete=function(j,o){var m=new c(j,this,o);if(!o.width>0){o.width=m.input.css("width")}var i=new a(m,b(m.id+"_auto_complete"),o);var e=new d(o,o.data);var n=false;var l=false;var h=null;function g(s){var p=o.url+"/"+encodeURI(s);for(var r in o.extraParams){p+="&"+r+"="+encodeURI(o.extraParams[r])}if(o.with_params&&typeof(o.with_params)=="function"){p+=o.with_params()}return p}function k(r,p){if(p){m.stopLoad();if(!m.receiveData(r,p)){return i.hideNow()}i.loadData(p);i.show()}else{i.hideNow()}}function f(p,r){if(!o.matchCase){r=r.toLowerCase()}var s=e.lookup(r);if(s){k(r,s)}if((!s||s.length<o.maxItemsToShow)&&(typeof o.url=="string")&&(o.url.length>0)){h=b.ajax({url:g(r),async:true,beforeSend:function(){m.showSpinner()},dataType:"json",complete:function(){m.hideSpinner()},success:function(q){e.store(r,q);k(r,e.merge(s,q))}})}else{m.stopLoad()}}m.input.bind("moveup",function(){i.moveUp()}).bind("movedown",function(){i.moveDown()}).bind("selectcurrent",function(){i.selectCurrent()}).bind("valuehide",function(){i.hide();m.stopLoad()}).bind("valuechange",f).bind("valueselected",function(q,p){m.lastSelected=p;this.prev=p;if(h){m.hideSpinner();h=null}m.setValue(p);e.flush()})};jQuery.fn.autocomplete=function(f,e,g){e=e||{};e.url=f;e.data=(g&&(typeof g=="object")&&(g.constructor==Array))?g:null;e.inputClass=e.inputClass||"ac_input";e.resultsClass=e.resultsClass||"ac_results";e.lineSeparator=e.lineSeparator||"\n";e.cellSeparator=e.cellSeparator||"|";e.minChars=e.minChars||2;e.delay=e.delay||400;e.matchCase=e.matchCase||0;e.matchSubset=e.matchSubset||true;e.matchContains=e.matchContains||false;e.cacheLength=e.cacheLength||1;e.mustMatch=e.mustMatch||0;e.extraParams=e.extraParams||{};e.loadingClass=e.loadingClass||"ac_loading";e.selectFirst=e.selectFirst||false;e.selectOnly=e.selectOnly||false;e.maxItemsToShow=e.maxItemsToShow||8;e.autoFill=e.autoFill||true;e.width=parseInt(e.width,10)||0;this.each(function(){var h=this;var i=new jQuery.autocomplete(h,e)});return this};jQuery.fn.autocompleteArray=function(f,e){return this.autocomplete(null,e,f)};jQuery.fn.indexOf=function(g){for(var f=0;f<this.length;f++){if(this[f]==g){return f}}return -1}})(jQuery);
(function(d){d.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(f,e){d.fx.step[e]=function(g){if(g.state==0){g.start=c(g.elem,e);g.end=b(g.end)}g.elem.style[e]="rgb("+[Math.max(Math.min(parseInt((g.pos*(g.end[0]-g.start[0]))+g.start[0]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[1]-g.start[1]))+g.start[1]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[2]-g.start[2]))+g.start[2]),255),0)].join(",")+")"}});function b(f){var e;if(f&&f.constructor==Array&&f.length==3){return f}if(e=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)){return[parseInt(e[1]),parseInt(e[2]),parseInt(e[3])]}if(e=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)){return[parseFloat(e[1])*2.55,parseFloat(e[2])*2.55,parseFloat(e[3])*2.55]}if(e=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}if(e=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}return a[d.trim(f).toLowerCase()]}function c(g,e){var f;do{f=d.curCSS(g,e);if(f!=""&&f!="transparent"||d.nodeName(g,"body")){break}e="backgroundColor"}while(g=g.parentNode);return b(f)}var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);
/*
 * Depend Class v0.1b : attach class based on first class in list of current element
 * File: jquery.dependClass.js
 * Copyright (c) 2009 Egor Hmelyoff, hmelyoff@gmail.com
 */


(function($) {
	// Init plugin function
	$.baseClass = function( obj ){
	  obj = $(obj);
	  var sClass = obj.get(0).className.match(/([^ ]+)/);
	  if( sClass && sClass[1] )
	    return sClass[1];

	  return false;
	};
	
	$.fn.addDependClass = function( className, delimiter ){
		var options = {
		  delimiter: delimiter ? delimiter : '-'
		}
		return this.each(function(){
		  var baseClass = $.baseClass(this);
		  if( baseClass )
    		$(this).addClass(baseClass + options.delimiter + className);
    	else {
    	  this.baseClass = false;
    	  $(this).addClass(className);
    	}
    	
		});
	};

	$.fn.removeDependClass = function( className, delimiter ){
		var options = {
		  delimiter: delimiter ? delimiter : '-'
		}
		return this.each(function(){
		  var baseClass = $.baseClass(this);

    	if( this.className == className || this.baseClass === false )
    	  $(this).removeClass(className);

		  else if( baseClass )
    		$(this).removeClass(baseClass + options.delimiter + className);
    	  
		});
	};

	$.fn.toggleDependClass = function( className, delimiter ){
		var options = {
		  delimiter: delimiter ? delimiter : '-'
		}
		return this.each(function(){
		  var baseClass = $.baseClass(this);
		  if( baseClass )
		    if( $(this).is("." + baseClass + options.delimiter + className) )
    		  $(this).removeClass(baseClass + options.delimiter + className);
    		else
    		  $(this).addClass(baseClass + options.delimiter + className);
		});
	};

	// end of closure
})(jQuery);
jQuery.cookie=function(b,j,m){if(typeof j!="undefined"){m=m||{};if(j===null){j="";m.expires=-1}var e="";if(m.expires&&(typeof m.expires=="number"||m.expires.toUTCString)){var f;if(typeof m.expires=="number"){f=new Date();f.setTime(f.getTime()+(m.expires*24*60*60*1000))}else{f=m.expires}e="; expires="+f.toUTCString()}var l=m.path?"; path="+(m.path):"";var g=m.domain?"; domain="+(m.domain):"";var a=m.secure?"; secure":"";document.cookie=[b,"=",encodeURIComponent(j),e,l,g,a].join("")}else{var d=null;if(document.cookie&&document.cookie!==""){var k=document.cookie.split(";");for(var h=0;h<k.length;h++){var c=jQuery.trim(k[h]);if(c.substring(0,b.length+1)==(b+"=")){d=decodeURIComponent(c.substring(b.length+1));break}}}return d}};
(function(d){d.fn.tabby=function(f){var g=d.extend({},d.fn.tabby.defaults,f);var h=d.fn.tabby.pressed;return this.each(function(){$this=d(this);var i=d.meta?d.extend({},g,$this.data()):g;$this.bind("keydown",function(k){var j=d.fn.tabby.catch_kc(k);if(16==j){h.shft=true}if(17==j){h.ctrl=true;setTimeout(function(){d.fn.tabby.pressed.ctrl=false},1000)}if(18==j){h.alt=true;setTimeout(function(){d.fn.tabby.pressed.alt=false},1000)}if(9==j&&!h.ctrl&&!h.alt){k.preventDefault;h.last=j;setTimeout(function(){d.fn.tabby.pressed.last=null},0);e(d(k.target).get(0),h.shft,i);return false}}).bind("keyup",function(j){if(16==d.fn.tabby.catch_kc(j)){h.shft=false}}).bind("blur",function(j){if(9==h.last){d(j.target).one("focus",function(k){h.last=null}).get(0).focus()}})})};d.fn.tabby.catch_kc=function(f){return f.keyCode?f.keyCode:f.charCode?f.charCode:f.which};d.fn.tabby.pressed={shft:false,ctrl:false,alt:false,last:null};function b(f){if(window.console&&window.console.log){window.console.log("textarea count: "+f.size())}}function e(i,h,g){var f=i.scrollTop;if(i.setSelectionRange){a(i,h,g)}else{if(document.selection){c(i,h,g)}}i.scrollTop=f}d.fn.tabby.defaults={tabString:String.fromCharCode(9)};function a(j,f,u){var t=j.selectionStart;var r=j.selectionEnd;if(t==r){if(f){if("\t"==j.value.substring(t-u.tabString.length,t)){j.value=j.value.substring(0,t-u.tabString.length)+j.value.substring(t);j.focus();j.setSelectionRange(t-u.tabString.length,t-u.tabString.length)}else{if("\t"==j.value.substring(t,t+u.tabString.length)){j.value=j.value.substring(0,t)+j.value.substring(t+u.tabString.length);j.focus();j.setSelectionRange(t,t)}}}else{j.value=j.value.substring(0,t)+u.tabString+j.value.substring(t);j.focus();j.setSelectionRange(t+u.tabString.length,t+u.tabString.length)}}else{var v=j.value.split("\n");var s=new Array();var l=0;var h=0;var g=false;for(var n in v){h=l+v[n].length;s.push({start:l,end:h,selected:(l<=t&&h>t)||(h>=r&&l<r)||(l>t&&h<r)});l=h+1}var k=0;for(var n in s){if(s[n].selected){var q=s[n].start+k;if(f&&u.tabString==j.value.substring(q,q+u.tabString.length)){j.value=j.value.substring(0,q)+j.value.substring(q+u.tabString.length);k-=u.tabString.length}else{if(!f){j.value=j.value.substring(0,q)+u.tabString+j.value.substring(q);k+=u.tabString.length}}}}j.focus();var p=t+((k>0)?u.tabString.length:(k<0)?-u.tabString.length:0);var m=r+k;j.setSelectionRange(p,m)}}function c(q,w,f){var p=document.selection.createRange();if(q==p.parentElement()){if(""==p.text){if(w){var l=p.getBookmark();p.moveStart("character",-f.tabString.length);if(f.tabString==p.text){p.text=""}else{p.moveToBookmark(l);p.moveEnd("character",f.tabString.length);if(f.tabString==p.text){p.text=""}}p.collapse(true);p.select()}else{p.text=f.tabString;p.collapse(false);p.select()}}else{var k=p.text;var n=k.length;var u=k.split("\r\n");var z=document.body.createTextRange();z.moveToElementText(q);z.setEndPoint("EndToStart",p);var m=z.text;var x=m.split("\r\n");var r=m.length;var y=document.body.createTextRange();y.moveToElementText(q);y.setEndPoint("StartToEnd",p);var v=y.text;var g=document.body.createTextRange();g.moveToElementText(q);g.setEndPoint("StartToEnd",z);var s=g.text;var h=d(q).html();d("#r3").text(r+" + "+n+" + "+v.length+" = "+h.length);if((r+s.length)<h.length){x.push("");r+=2;if(w&&f.tabString==u[0].substring(0,f.tabString.length)){u[0]=u[0].substring(f.tabString.length)}else{if(!w){u[0]=f.tabString+u[0]}}}else{if(w&&f.tabString==x[x.length-1].substring(0,f.tabString.length)){x[x.length-1]=x[x.length-1].substring(f.tabString.length)}else{if(!w){x[x.length-1]=f.tabString+x[x.length-1]}}}for(var t=1;t<u.length;t++){if(w&&f.tabString==u[t].substring(0,f.tabString.length)){u[t]=u[t].substring(f.tabString.length)}else{if(!w){u[t]=f.tabString+u[t]}}}if(1==x.length&&0==r){if(w&&f.tabString==u[0].substring(0,f.tabString.length)){u[0]=u[0].substring(f.tabString.length)}else{if(!w){u[0]=f.tabString+u[0]}}}if((r+n+v.length)<h.length){u.push("");n+=2}z.text=x.join("\r\n");p.text=u.join("\r\n");var j=document.body.createTextRange();j.moveToElementText(q);if(0<r){j.setEndPoint("StartToEnd",z)}else{j.setEndPoint("StartToStart",z)}j.setEndPoint("EndToEnd",p);j.select()}}}})(jQuery);
/*
 * XMLformat v0.2b : format one string XML or not good formatted XML to good tab-formatted XML
 * File: jquery.xmlformat.js
 * Copyright (c) 2009 Egor Hmelyoff, hmelyoff@gmail.com
 */


(function($) {
	// plugin definition
	
	var uid = 0;
	var getId = function(){
	  uid++;
	  return uid;
	};
	
	var OPTIONS = {
		isDebug: true,
		level: 0,
		
		ELEMENT_NODE   : 1,
		ATTRIBUTE_NODE : 2,
		TEXT_NODE      : 3,
		DOCUMENT_NODE  : 9,
		
		NODE_BLOCK     : 'block',
		NODE_INLINE    : 'inline',
		NODE_SELFCLOSED  : 'selfclosed',
		
		nodeTypes: {
			block      : ["DIV", "P", "UL", "OL", "LI"],
			inline     : ["STRONG", "B", "EM", "I", "SPAN", "A", "OBJECT", "DEL"],
			selfclosed   : ["BR", "HR", "IMG", "EMBED", "PARAM"]
		},
		
		attrFilter: [ // specific attrs for remove
		 "contentEditable",
		 /^jQuery(.*)?$/,
		 "start",
		 "loop"
		]
	};

	// Init global plugin method
	$.XMLformat = function(text, options){
		OPTIONS = $.extend(OPTIONS, options ? options : {});
    // save all links
		var links = save(text);
		text = links.text;
		OPTIONS.links = links.links;

		// clean up before actions
		text = cleanup(text);
		text = indent() + extract($(text));
		
		if($.browser.msie){
		  OPTIONS.objects = links.objects;
		  text = back(text);
		}

		return (text);
	};

	// Init plugin function
	$.fn.XMLformat = function(options){
		OPTIONS = $.extend(OPTIONS, options);
		
		return this.each(function(){
			XMLformat.call(this);
		});
	};

	var XMLformat = function(){
		var obj = $(this);
		switch(this.nodeName){
			case 'TEXTAREA':
				obj.val($.XMLformat(obj.val()));
				break;
			default:
				debug('unknown tag —> no actions');
				break;
		};
		
	};
	
	var cleanup = function(text){
		// remove all string modifiers
		text = text.replace(/[\n\t\0\v\f\r]/g, " ");
		
		// remove double[or more] spaces
		text = text.replace(/ {2,}/g, " ");

  	// remove spaces between block tags
  	var blocks = "div|p|hr|ul|ol|li|h1|h2|h3|h4|h5|h6|object|param|table|tbody|tr|td|th";
  	var rBlocks = new RegExp("<(\/)?(" + blocks + "){1}(\/)?> *<(" + blocks + "){1}>", "g")
  	text = text.replace(rBlocks, "<$1$2$3><$4>");

		// remove space at the beginning of the string
		// text = text.replace(/^ /g, "");
		
		// remove spaces between tags
		// text = text.replace(/<\/([^\/>]*)> *</g, "<\/$1><");
		// text = text.replace(/<([^ \>]*)? ?\/> *</g, "<$1 \/><");

		// remove spaces inside tag at the beginning/end of string
		// text = text.replace(/<(.*)?> *(.*?) *<\/ ?\1>/g, "<$1>$2</$1>");

		return (text);
	};
	
	var save = function(text){

  	var pattern_object = /<(object)([^>]*)>(.*?)(<\/ ?\1>)/ig;
	  
	  var result = [];
	  var objects = [];
	  text = text.replace(/img([^(:src=)]*)?src=(['"])([^'"]*)/gi, function(){
	    var stamp = "xmlformat-" + getId();//(new Date()).getTime() + Math.round(Math.random()*9999);
	    result.push({ url: arguments[3], stamp: stamp })
	    return "img" + arguments[1] + "src=" + arguments[2] + "/images/d.gif?" + stamp;
	  });
/*
	  text = text.replace(/href=(['"])([^'"]*)/gi, function(){
	    var stamp = "xmlformat-" + getId();//(new Date()).getTime() + Math.round(Math.random()*9999);
	    result.push({ url: arguments[2], stamp: stamp })
	    return "href=" + arguments[1] + stamp;
	  });
*/
		if($.browser.msie)
  	  text = text.replace(pattern_object, function(){
  	    var stamp = "xmlformat-" + getId();//(new Date()).getTime() + Math.round(Math.random()*9999);
  	    objects.push({ object: arguments[0], stamp: stamp })
  	    return '<img type="xmlformat_object" src="/images/d.gif?' + stamp + '" />';
      })

	  return { text: text, links: result, objects: objects };
	};
	
	var back = function(text){
  	var pattern_img = /<img([^>]*)\/?>/ig;

    return text.replace(pattern_img, function(){
      var attrs = getAttrs(arguments[1]);
      if(attrs.type == "xmlformat_object"){
        if(attrs.src){
          for (var i=0; i < OPTIONS.objects.length; i++) {
            if(attrs.src.split("?")[1] == OPTIONS.objects[i].stamp)
              return OPTIONS.objects[i].object;
            
          };
        }
        return "";
      } else {
        return arguments[0]
      }
    })

	};

  var getAttrs = function(string){
    var result;
    var attrs = {};
    var pattern = /(\w+)=(["']{1})([^\2]*?)(\2{1})/g;
    while((result = pattern.exec(string)) != null){
      attrs[result[1]] = result[3];
    }
    return attrs;
  };
	
	var extract = function(data, node){
		var result = new String();
		data.each(function(i){
			switch(this.nodeType){
				case OPTIONS.ELEMENT_NODE:
					result += createElement(this);
					break;

				case OPTIONS.TEXT_NODE:
				  if(data.length == 1 && node){
				    result += node.innerHTML;
				  } else {
  					result += this.nodeValue;
				  }
					break;
			};
		});
		return (result);
	};
	
	var createElement = function(node){
		var result = new String();

		// get next node if exist;
		var next = getNextNode(node);
		var prev = getPrevNode(node);

		switch(nodeType(node)){

			case OPTIONS.NODE_BLOCK:

				OPTIONS.level++;

				result += "<" + node.tagName.toLowerCase() + createAttrs(node) + ">";
					if(node.childNodes){
						if(nodeType(node.childNodes[0]) == OPTIONS.NODE_BLOCK){
							result += "\n" + indent();
						}
						result += extract($(node.childNodes), node);
					}
				result += "</" + node.tagName.toLowerCase() + ">";

				OPTIONS.level--;
				result += "\n";

				if(next)
					result += indent();
				else {
					OPTIONS.level--;
					result += indent();
					OPTIONS.level++;
				}
				
				break;


			case OPTIONS.NODE_INLINE:

				result += "<" + node.tagName.toLowerCase() + createAttrs(node) + ">";
					if(node.childNodes)
						result += extract($(node.childNodes), node);
				result += "</" + node.tagName.toLowerCase() + ">";

				break;


			case OPTIONS.NODE_SELFCLOSED:

				result += "<" + node.tagName.toLowerCase() + createAttrs(node) + " />";
				if(next && nodeType(next) == OPTIONS.NODE_BLOCK)
					result += "\n" + indent();

				break;
				
			default:
				break;
		};

		return (result);
	};
	
	var createAttrs = function(node){
		var result = new String();
			for (var i=0; i < node.attributes.length; i++) {
			  if(node.attributes[i].nodeValue && filterAttrs(node.attributes[i].nodeName)){
			    var name = node.attributes[i].nodeName.toLowerCase();
			    var value = node.attributes[i].nodeValue;
			    if(name == "src" || name == "href"){
			      for (var j=0; j < OPTIONS.links.length; j++) {
			        if(value.split("xmlformat")[1] && ('xmlformat' + value.split("xmlformat")[1]) == OPTIONS.links[j].stamp){
			        //if((value.split("?")[1] && value.split("?")[1] == OPTIONS.links[j].stamp) || value == OPTIONS.links[j].stamp){
		            value = OPTIONS.links[j].url;
		          }
			      };
			    }
				  result += ' ' + name + '="' + value + '"';
				}
			};
		return (result);
	}
	
	var filterAttrs = function(name){
	  for (var i=0; i < OPTIONS.attrFilter.length; i++) {
	    if(OPTIONS.attrFilter[i].test){
	      if(OPTIONS.attrFilter[i].test(name))
	        return false;
	    } else if(OPTIONS.attrFilter[i].toLowerCase() == name.toLowerCase())
	      return false;
	  };
	  return true;
	}
	
	var nodeType = function(node){
	  if(node){
  		switch(node.nodeType){
  			case OPTIONS.ELEMENT_NODE:
  				for(key in OPTIONS.nodeTypes){
  					for (var i=0; i < OPTIONS.nodeTypes[key].length; i++) {
  						if(OPTIONS.nodeTypes[key][i] == node.tagName)
  							return key;
  					};
  				}
  				break;

  			case OPTIONS.TEXT_NODE:
  				return OPTIONS.NODE_INLINE;
  				break;
  		}
  		// if undefined tag -> consider that is block node
  		return OPTIONS.NODE_BLOCK;
  	}
  	return false;
	};
	
	var indent = function(){
		var result = new String();

		for (var i=0; i < OPTIONS.level; i++) {
			result += "\t";
		};
		return (result);
	};

	var getPrevNode = function(node){
		_prev = $(node).prev();
		if(_prev.length) _prev = _prev.get(0);
		else _prev = null;
		return _prev;
	};
	
	var getNextNode = function(node){
		_next = $(node).next();
		if(_next.length) _next = _next.get(0);
		else _next = null;
		return _next;
	};
	
	// private function for debugging
	function debug(str) {
		if (window.console && window.console.log && OPTIONS.isDebug)
			window.console.log("[XMLformat: '" + str + "']");
	};

	// end of closure
})(jQuery);
(function(c){var a=c.scrollTo=function(f,e,d){c(window).scrollTo(f,e,d)};a.defaults={axis:"xy",duration:parseFloat(c.fn.jquery)>=1.3?0:1};a.window=function(d){return c(window)._scrollable()};c.fn._scrollable=function(){return this.map(function(){var e=this,d=!e.nodeName||c.inArray(e.nodeName.toLowerCase(),["iframe","#document","html","body"])!=-1;if(!d){return e}var f=(e.contentWindow||e).document||e.ownerDocument||e;return c.browser.safari||f.compatMode=="BackCompat"?f.body:f.documentElement})};c.fn.scrollTo=function(f,e,d){if(typeof e=="object"){d=e;e=0}if(typeof d=="function"){d={onAfter:d}}if(f=="max"){f=9000000000}d=c.extend({},a.defaults,d);e=e||d.speed||d.duration;d.queue=d.queue&&d.axis.length>1;if(d.queue){e/=2}d.offset=b(d.offset);d.over=b(d.over);return this._scrollable().each(function(){var l=this,j=c(l),k=f,i,g={},m=j.is("html,body");switch(typeof k){case"number":case"string":if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(k)){k=b(k);break}k=c(k,this);case"object":if(k.is||k.style){i=(k=c(k)).offset()}}c.each(d.axis.split(""),function(q,r){var s=r=="x"?"Left":"Top",u=s.toLowerCase(),p="scroll"+s,o=l[p],n=a.max(l,r);if(i){g[p]=i[u]+(m?0:o-j.offset()[u]);if(d.margin){g[p]-=parseInt(k.css("margin"+s))||0;g[p]-=parseInt(k.css("border"+s+"Width"))||0}g[p]+=d.offset[u]||0;if(d.over[u]){g[p]+=k[r=="x"?"width":"height"]()*d.over[u]}}else{var t=k[u];g[p]=t.slice&&t.slice(-1)=="%"?parseFloat(t)/100*n:t}if(/^\d+$/.test(g[p])){g[p]=g[p]<=0?0:Math.min(g[p],n)}if(!q&&d.queue){if(o!=g[p]){h(d.onAfterFirst)}delete g[p]}});h(d.onAfter);function h(n){j.animate(g,e,d.easing,n&&function(){n.call(this,f,d)})}}).end()};a.max=function(j,i){var h=i=="x"?"Width":"Height",e="scroll"+h;if(!c(j).is("html,body")){return j[e]-c(j)[h.toLowerCase()]()}var g="client"+h,f=j.ownerDocument.documentElement,d=j.ownerDocument.body;return Math.max(f[e],d[e])-Math.min(f[g],d[g])};function b(d){return typeof d=="object"?d:{top:d,left:d}}})(jQuery);

(function($) {

	$.fn.LAMswitcher = function( callback, options ){
		var OPTIONS = $.extend({
		  className: "selected",
		  delay: 0
		}, options ? options : {});
		
		var self = this;
    
		return this.each(function(){
			$(this).click(function(){
			  var node = this;
			  self.removeDependClass(OPTIONS.className);
			  $(this).addDependClass(OPTIONS.className);
			  if( $.isFunction(callback) )
			    if( OPTIONS.delay )
    			  setTimeout(function(){
    			    callback.call(node);
    			  }, OPTIONS.delay);
    			else
    			  callback.call(node);

			  return false;
			});
		});
	};
    
})(jQuery);

/* Global browsers definition */

(function($) {
  
  if( !$.browser.msie )
	  $(document.documentElement).addClass("e-loaded");

	if( $.browser.safari )
		$(document.documentElement)
		  .addClass("e-webkit");

	if( $.browser.mozilla )
		$(document.documentElement).addClass("e-gecko");

	if( $.browser.opera )
		$(document.documentElement).addClass("e-opera");


})(jQuery);

/* Global browsers definition (end) */
/* Global base events definition */

(function($) {

	$(document).ready(function(){

	  $(".hovered, .j-hovered")
  	  .live("mouseover", function(){
    		$(this).addDependClass("hover");
  	  })
  	  .live("mouseout", function(){
    		$(this).removeDependClass("hover");
  	  })
  	  
  	$(".j-collapse")
  	  .live("click", function(){
  	    $(this).parents(".j-collapsed").toggleDependClass("collapsed");
  	    return false;
  	  })

	});

})(jQuery);

/* Global base events definition (end) */
/* Placeholder for inputs */

(function($) {
  
  $(document).ready(function(){
    GLOBAL.reInit(function(){
      $("input[placeholder], textarea[placeholder]").not("[prettysearch=yes]").each(function(){
        new g_placeholder(this);
      })
    })
  })
  
  this.g_placeholder = function(input){
  	return this.init.apply(this, arguments);
  }
  
  g_placeholder.prototype = {
    init: function(obj){
      this.ptr = $(obj);

      this.placeholder = this.ptr.attr("placeholder");
      this.ptr.removeAttr("placeholder");

      this.create();
      this.bindEvents();
      
      if(this.ptr.val() != '')
        this.f_placeholder(false);
    },
    create: function(){
      this.domNode = $("<span>");
      this.domNode.css({
        display: "inline-block",
        position: "relative",
        width: "100%"
      })
      this.ptr.wrap(this.domNode);

      this.placeholderNode = $("<span>");
      this.placeholderNode
        .text(this.placeholder)
        .css({ position: "absolute", left: 3, top: 3, height: "1.5em", color: "gray", zIndex: 1 })
      this.ptr.after(this.placeholderNode);
    },
    bindEvents: function(){
      var $this = this;
      this.ptr
        .focus(function(){
          $this.f_placeholder(false);
        })
        .blur(function(){
          if($this.ptr.val() == '')
            $this.f_placeholder(true);
        })
      this.placeholderNode
        .mouseup(function(){
          if(!$this.ptr.is(":disabled"))
            $this.ptr.focus();
        })
    },
    f_placeholder: function(status){
      if(status)
        this.placeholderNode.show()
      else
        this.placeholderNode.hide()
    }
  }
  
})(jQuery);

/* Placeholder for inputs (end) */

/* SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write("<script id=__ie_ondomload defer=true src=//:><\/script>");J=C("__ie_ondomload");if(J){I(J,"onreadystatechange",S)}}catch(q){}}if(h.webkit&&typeof K.readyState!=b){Z=setInterval(function(){if(/loaded|complete/.test(K.readyState)){E()}},10)}if(typeof K.addEventListener!=b){K.addEventListener("DOMContentLoaded",E,null)}R(E)}();function S(){if(J.readyState=="complete"){J.parentNode.removeChild(J);E()}}function E(){if(e){return }if(h.ie&&h.win){var v=a("span");try{var u=K.getElementsByTagName("body")[0].appendChild(v);u.parentNode.removeChild(u)}catch(w){return }}e=true;if(Z){clearInterval(Z);Z=null}var q=o.length;for(var r=0;r<q;r++){o[r]()}}function f(q){if(e){q()}else{o[o.length]=q}}function R(r){if(typeof j.addEventListener!=b){j.addEventListener("load",r,false)}else{if(typeof K.addEventListener!=b){K.addEventListener("load",r,false)}else{if(typeof j.attachEvent!=b){I(j,"onload",r)}else{if(typeof j.onload=="function"){var q=j.onload;j.onload=function(){q();r()}}else{j.onload=r}}}}}function H(){var t=N.length;for(var q=0;q<t;q++){var u=N[q].id;if(h.pv[0]>0){var r=C(u);if(r){N[q].width=r.getAttribute("width")?r.getAttribute("width"):"0";N[q].height=r.getAttribute("height")?r.getAttribute("height"):"0";if(c(N[q].swfVersion)){if(h.webkit&&h.webkit<312){Y(r)}W(u,true)}else{if(N[q].expressInstall&&!A&&c("6.0.65")&&(h.win||h.mac)){k(N[q])}else{O(r)}}}}else{W(u,true)}}}function Y(t){var q=t.getElementsByTagName(Q)[0];if(q){var w=a("embed"),y=q.attributes;if(y){var v=y.length;for(var u=0;u<v;u++){if(y[u].nodeName=="DATA"){w.setAttribute("src",y[u].nodeValue)}else{w.setAttribute(y[u].nodeName,y[u].nodeValue)}}}var x=q.childNodes;if(x){var z=x.length;for(var r=0;r<z;r++){if(x[r].nodeType==1&&x[r].nodeName=="PARAM"){w.setAttribute(x[r].getAttribute("name"),x[r].getAttribute("value"))}}}t.parentNode.replaceChild(w,t)}}function k(w){A=true;var u=C(w.id);if(u){if(w.altContentId){var y=C(w.altContentId);if(y){M=y;l=w.altContentId}}else{M=G(u)}if(!(/%$/.test(w.width))&&parseInt(w.width,10)<310){w.width="310"}if(!(/%$/.test(w.height))&&parseInt(w.height,10)<137){w.height="137"}K.title=K.title.slice(0,47)+" - Flash Player Installation";var z=h.ie&&h.win?"ActiveX":"PlugIn",q=K.title,r="MMredirectURL="+j.location+"&MMplayerType="+z+"&MMdoctitle="+q,x=w.id;if(h.ie&&h.win&&u.readyState!=4){var t=a("div");x+="SWFObjectNew";t.setAttribute("id",x);u.parentNode.insertBefore(t,u);u.style.display="none";var v=function(){u.parentNode.removeChild(u)};I(j,"onload",v)}U({data:w.expressInstall,id:m,width:w.width,height:w.height},{flashvars:r},x)}}function O(t){if(h.ie&&h.win&&t.readyState!=4){var r=a("div");t.parentNode.insertBefore(r,t);r.parentNode.replaceChild(G(t),r);t.style.display="none";var q=function(){t.parentNode.removeChild(t)};I(j,"onload",q)}else{t.parentNode.replaceChild(G(t),t)}}function G(v){var u=a("div");if(h.win&&h.ie){u.innerHTML=v.innerHTML}else{var r=v.getElementsByTagName(Q)[0];if(r){var w=r.childNodes;if(w){var q=w.length;for(var t=0;t<q;t++){if(!(w[t].nodeType==1&&w[t].nodeName=="PARAM")&&!(w[t].nodeType==8)){u.appendChild(w[t].cloneNode(true))}}}}}return u}function U(AG,AE,t){var q,v=C(t);if(v){if(typeof AG.id==b){AG.id=t}if(h.ie&&h.win){var AF="";for(var AB in AG){if(AG[AB]!=Object.prototype[AB]){if(AB.toLowerCase()=="data"){AE.movie=AG[AB]}else{if(AB.toLowerCase()=="styleclass"){AF+=' class="'+AG[AB]+'"'}else{if(AB.toLowerCase()!="classid"){AF+=" "+AB+'="'+AG[AB]+'"'}}}}}var AD="";for(var AA in AE){if(AE[AA]!=Object.prototype[AA]){AD+='<param name="'+AA+'" value="'+AE[AA]+'" />'}}v.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AF+">"+AD+"</object>";i[i.length]=AG.id;q=C(AG.id)}else{if(h.webkit&&h.webkit<312){var AC=a("embed");AC.setAttribute("type",P);for(var z in AG){if(AG[z]!=Object.prototype[z]){if(z.toLowerCase()=="data"){AC.setAttribute("src",AG[z])}else{if(z.toLowerCase()=="styleclass"){AC.setAttribute("class",AG[z])}else{if(z.toLowerCase()!="classid"){AC.setAttribute(z,AG[z])}}}}}for(var y in AE){if(AE[y]!=Object.prototype[y]){if(y.toLowerCase()!="movie"){AC.setAttribute(y,AE[y])}}}v.parentNode.replaceChild(AC,v);q=AC}else{var u=a(Q);u.setAttribute("type",P);for(var x in AG){if(AG[x]!=Object.prototype[x]){if(x.toLowerCase()=="styleclass"){u.setAttribute("class",AG[x])}else{if(x.toLowerCase()!="classid"){u.setAttribute(x,AG[x])}}}}for(var w in AE){if(AE[w]!=Object.prototype[w]&&w.toLowerCase()!="movie"){F(u,w,AE[w])}}v.parentNode.replaceChild(u,v);q=u}}}return q}function F(t,q,r){var u=a("param");u.setAttribute("name",q);u.setAttribute("value",r);t.appendChild(u)}function X(r){var q=C(r);if(q&&(q.nodeName=="OBJECT"||q.nodeName=="EMBED")){if(h.ie&&h.win){if(q.readyState==4){B(r)}else{j.attachEvent("onload",function(){B(r)})}}else{q.parentNode.removeChild(q)}}}function B(t){var r=C(t);if(r){for(var q in r){if(typeof r[q]=="function"){r[q]=null}}r.parentNode.removeChild(r)}}function C(t){var q=null;try{q=K.getElementById(t)}catch(r){}return q}function a(q){return K.createElement(q)}function I(t,q,r){t.attachEvent(q,r);d[d.length]=[t,q,r]}function c(t){var r=h.pv,q=t.split(".");q[0]=parseInt(q[0],10);q[1]=parseInt(q[1],10)||0;q[2]=parseInt(q[2],10)||0;return(r[0]>q[0]||(r[0]==q[0]&&r[1]>q[1])||(r[0]==q[0]&&r[1]==q[1]&&r[2]>=q[2]))?true:false}function V(v,r){if(h.ie&&h.mac){return }var u=K.getElementsByTagName("head")[0],t=a("style");t.setAttribute("type","text/css");t.setAttribute("media","screen");if(!(h.ie&&h.win)&&typeof K.createTextNode!=b){t.appendChild(K.createTextNode(v+" {"+r+"}"))}u.appendChild(t);if(h.ie&&h.win&&typeof K.styleSheets!=b&&K.styleSheets.length>0){var q=K.styleSheets[K.styleSheets.length-1];if(typeof q.addRule==Q){q.addRule(v,r)}}}function W(t,q){var r=q?"visible":"hidden";if(e&&C(t)){C(t).style.visibility=r}else{V("#"+t,"visibility:"+r)}}function g(s){var r=/[\\\"<>\.;]/;var q=r.exec(s)!=null;return q?encodeURIComponent(s):s}var D=function(){if(h.ie&&h.win){window.attachEvent("onunload",function(){var w=d.length;for(var v=0;v<w;v++){d[v][0].detachEvent(d[v][1],d[v][2])}var t=i.length;for(var u=0;u<t;u++){X(i[u])}for(var r in h){h[r]=null}h=null;for(var q in swfobject){swfobject[q]=null}swfobject=null})}}();return{registerObject:function(u,q,t){if(!h.w3cdom||!u||!q){return }var r={};r.id=u;r.swfVersion=q;r.expressInstall=t?t:false;N[N.length]=r;W(u,false)},getObjectById:function(v){var q=null;if(h.w3cdom){var t=C(v);if(t){var u=t.getElementsByTagName(Q)[0];if(!u||(u&&typeof t.SetVariable!=b)){q=t}else{if(typeof u.SetVariable!=b){q=u}}}}return q},embedSWF:function(x,AE,AB,AD,q,w,r,z,AC){if(!h.w3cdom||!x||!AE||!AB||!AD||!q){return }AB+="";AD+="";if(c(q)){W(AE,false);var AA={};if(AC&&typeof AC===Q){for(var v in AC){if(AC[v]!=Object.prototype[v]){AA[v]=AC[v]}}}AA.data=x;AA.width=AB;AA.height=AD;var y={};if(z&&typeof z===Q){for(var u in z){if(z[u]!=Object.prototype[u]){y[u]=z[u]}}}if(r&&typeof r===Q){for(var t in r){if(r[t]!=Object.prototype[t]){if(typeof y.flashvars!=b){y.flashvars+="&"+t+"="+r[t]}else{y.flashvars=t+"="+r[t]}}}}f(function(){U(AA,y,AE);if(AA.id==AE){W(AE,true)}})}else{if(w&&!A&&c("6.0.65")&&(h.win||h.mac)){A=true;W(AE,false);f(function(){var AF={};AF.id=AF.altContentId=AE;AF.width=AB;AF.height=AD;AF.expressInstall=w;k(AF)})}}},getFlashPlayerVersion:function(){return{major:h.pv[0],minor:h.pv[1],release:h.pv[2]}},hasFlashPlayerVersion:c,createSWF:function(t,r,q){if(h.w3cdom){return U(t,r,q)}else{return undefined}},removeSWF:function(q){if(h.w3cdom){X(q)}},createCSS:function(r,q){if(h.w3cdom){V(r,q)}},addDomLoadEvent:f,addLoadEvent:R,getQueryParamValue:function(v){var u=K.location.search||K.location.hash;if(v==null){return g(u)}if(u){var t=u.substring(1).split("&");for(var r=0;r<t.length;r++){if(t[r].substring(0,t[r].indexOf("="))==v){return g(t[r].substring((t[r].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(A&&M){var q=C(m);if(q){q.parentNode.replaceChild(M,q);if(l){W(l,true);if(h.ie&&h.win){M.style.display="block"}}M=null;l=null;A=false}}}}}();
/**
 * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
 *
 * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/,  http://www.vinterwebb.se/
 *
 * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilz�n and Mammon Media and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */


/* ******************* */
/* Constructor & Init  */
/* ******************* */
var SWFUpload;

if (SWFUpload == undefined) {
	SWFUpload = function (settings) {
		this.initSWFUpload(settings);
	};
}

SWFUpload.prototype.initSWFUpload = function (settings) {
	try {
		this.customSettings = {};	// A container where developers can place their own settings associated with this instance.
		this.settings = settings;
		this.eventQueue = [];
		this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
		this.movieElement = null;


		// Setup global control tracking
		SWFUpload.instances[this.movieName] = this;

		// Load the settings.  Load the Flash movie.
		this.initSettings();
		this.loadFlash();
		this.displayDebugInfo();
	} catch (ex) {
		delete SWFUpload.instances[this.movieName];
		throw ex;
	}
};

/* *************** */
/* Static Members  */
/* *************** */
SWFUpload.instances = {};
SWFUpload.movieCount = 0;
SWFUpload.version = "2.2.0 Beta 3";
SWFUpload.QUEUE_ERROR = {
	QUEUE_LIMIT_EXCEEDED	  		: -100,
	FILE_EXCEEDS_SIZE_LIMIT  		: -110,
	ZERO_BYTE_FILE			  		: -120,
	INVALID_FILETYPE		  		: -130
};
SWFUpload.UPLOAD_ERROR = {
	HTTP_ERROR				  		: -200,
	MISSING_UPLOAD_URL	      		: -210,
	IO_ERROR				  		: -220,
	SECURITY_ERROR			  		: -230,
	UPLOAD_LIMIT_EXCEEDED	  		: -240,
	UPLOAD_FAILED			  		: -250,
	SPECIFIED_FILE_ID_NOT_FOUND		: -260,
	FILE_VALIDATION_FAILED	  		: -270,
	FILE_CANCELLED			  		: -280,
	UPLOAD_STOPPED					: -290
};
SWFUpload.FILE_STATUS = {
	QUEUED		 : -1,
	IN_PROGRESS	 : -2,
	ERROR		 : -3,
	COMPLETE	 : -4,
	CANCELLED	 : -5
};
SWFUpload.BUTTON_ACTION = {
	SELECT_FILE  : -100,
	SELECT_FILES : -110,
	START_UPLOAD : -120
};
SWFUpload.CURSOR = {
	ARROW : -1,
	HAND : -2
};
SWFUpload.WINDOW_MODE = {
	WINDOW : "window",
	TRANSPARENT : "transparent",
	OPAQUE : "opaque"
};

/* ******************** */
/* Instance Members  */
/* ******************** */

// Private: initSettings ensures that all the
// settings are set, getting a default value if one was not assigned.
SWFUpload.prototype.initSettings = function () {
	this.ensureDefault = function (settingName, defaultValue) {
		this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
	};
	
	// Upload backend settings
	this.ensureDefault("upload_url", "");
	this.ensureDefault("file_post_name", "Filedata");
	this.ensureDefault("post_params", {});
	this.ensureDefault("use_query_string", false);
	this.ensureDefault("requeue_on_error", false);
	this.ensureDefault("http_success", []);
	
	// File Settings
	this.ensureDefault("file_types", "*.*");
	this.ensureDefault("file_types_description", "All Files");
	this.ensureDefault("file_size_limit", 0);	// Default zero means "unlimited"
	this.ensureDefault("file_upload_limit", 0);
	this.ensureDefault("file_queue_limit", 0);

	// Flash Settings
	this.ensureDefault("flash_url", "swfupload.swf");
	this.ensureDefault("prevent_swf_caching", true);
	
	// Button Settings
	this.ensureDefault("button_image_url", "");
	this.ensureDefault("button_width", 1);
	this.ensureDefault("button_height", 1);
	this.ensureDefault("button_text", "");
	this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
	this.ensureDefault("button_text_top_padding", 0);
	this.ensureDefault("button_text_left_padding", 0);
	this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
	this.ensureDefault("button_disabled", false);
	this.ensureDefault("button_placeholder_id", null);
	this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
	this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
	
	// Debug Settings
	this.ensureDefault("debug", false);
	this.settings.debug_enabled = this.settings.debug;	// Here to maintain v2 API
	
	// Event Handlers
	this.settings.return_upload_start_handler = this.returnUploadStart;
	this.ensureDefault("swfupload_loaded_handler", null);
	this.ensureDefault("file_dialog_start_handler", null);
	this.ensureDefault("file_queued_handler", null);
	this.ensureDefault("file_queue_error_handler", null);
	this.ensureDefault("file_dialog_complete_handler", null);
	
	this.ensureDefault("upload_start_handler", null);
	this.ensureDefault("upload_progress_handler", null);
	this.ensureDefault("upload_error_handler", null);
	this.ensureDefault("upload_success_handler", null);
	this.ensureDefault("upload_complete_handler", null);
	
	this.ensureDefault("debug_handler", this.debugMessage);

	this.ensureDefault("custom_settings", {});

	// Other settings
	this.customSettings = this.settings.custom_settings;
	
	// Update the flash url if needed
	if (this.settings.prevent_swf_caching) {
		this.settings.flash_url = this.settings.flash_url + "?swfuploadrnd=" + Math.floor(Math.random() * 999999999);
	}
	
	delete this.ensureDefault;
};

SWFUpload.prototype.loadFlash = function () {
	if (this.settings.button_placeholder_id !== "") {
		this.replaceWithFlash();
	} else {
		this.appendFlash();
	}
};

// Private: appendFlash gets the HTML tag for the Flash
// It then appends the flash to the body
SWFUpload.prototype.appendFlash = function () {
	var targetElement, container;

	// Make sure an element with the ID we are going to use doesn't already exist
	if (document.getElementById(this.movieName) !== null) {
		throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
	}

	// Get the body tag where we will be adding the flash movie
	targetElement = document.getElementsByTagName("body")[0];

	if (targetElement == undefined) {
		throw "Could not find the 'body' element.";
	}

	// Append the container and load the flash
	container = document.createElement("div");
	container.style.width = "1px";
	container.style.height = "1px";
	container.style.overflow = "hidden";

	targetElement.appendChild(container);
	container.innerHTML = this.getFlashHTML();	// Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)

	// Fix IE Flash/Form bug
	if (window[this.movieName] == undefined) {
		window[this.movieName] = this.getMovieElement();
	}
	
	
};

// Private: replaceWithFlash replaces the button_placeholder element with the flash movie.
SWFUpload.prototype.replaceWithFlash = function () {
	var targetElement, tempParent;

	// Make sure an element with the ID we are going to use doesn't already exist
	if (document.getElementById(this.movieName) !== null) {
		throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
	}

	// Get the element where we will be placing the flash movie
	targetElement = document.getElementById(this.settings.button_placeholder_id);

	if (targetElement == undefined) {
		throw "Could not find the placeholder element.";
	}

	// Append the container and load the flash
	tempParent = document.createElement("div");
	tempParent.innerHTML = this.getFlashHTML();	// Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
	targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);

	// Fix IE Flash/Form bug
	if (window[this.movieName] == undefined) {
		window[this.movieName] = this.getMovieElement();
	}
	
};

// Private: getFlashHTML generates the object tag needed to embed the flash in to the document
SWFUpload.prototype.getFlashHTML = function () {
	// Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
	return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
				'<param name="wmode" value="', this.settings.button_window_mode , '" />',
				'<param name="movie" value="', this.settings.flash_url, '" />',
				'<param name="quality" value="high" />',
				'<param name="menu" value="false" />',
				'<param name="allowScriptAccess" value="always" />',
				'<param name="flashvars" value="' + this.getFlashVars() + '" />',
				'</object>'].join("");
};

// Private: getFlashVars builds the parameter string that will be passed
// to flash in the flashvars param.
SWFUpload.prototype.getFlashVars = function () {
	// Build a string from the post param object
	var paramString = this.buildParamString();
	var httpSuccessString = this.settings.http_success.join(",");
	
	// Build the parameter string
	return ["movieName=", encodeURIComponent(this.movieName),
			"&amp;uploadURL=", encodeURIComponent(this.settings.upload_url),
			"&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string),
			"&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
			"&amp;httpSuccess=", encodeURIComponent(httpSuccessString),
			"&amp;params=", encodeURIComponent(paramString),
			"&amp;filePostName=", encodeURIComponent(this.settings.file_post_name),
			"&amp;fileTypes=", encodeURIComponent(this.settings.file_types),
			"&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
			"&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
			"&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
			"&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
			"&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
			"&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
			"&amp;buttonWidth=", encodeURIComponent(this.settings.button_width),
			"&amp;buttonHeight=", encodeURIComponent(this.settings.button_height),
			"&amp;buttonText=", encodeURIComponent(this.settings.button_text),
			"&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
			"&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
			"&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
			"&amp;buttonAction=", encodeURIComponent(this.settings.button_action),
			"&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
			"&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor)
		].join("");
};

// Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
// The element is cached after the first lookup
SWFUpload.prototype.getMovieElement = function () {
	if (this.movieElement == undefined) {
		this.movieElement = document.getElementById(this.movieName);
	}

	if (this.movieElement === null) {
		throw "Could not find Flash element";
	}
	
	return this.movieElement;
};

// Private: buildParamString takes the name/value pairs in the post_params setting object
// and joins them up in to a string formatted "name=value&amp;name=value"
SWFUpload.prototype.buildParamString = function () {
	var postParams = this.settings.post_params; 
	var paramStringPairs = [];

	if (typeof(postParams) === "object") {
		for (var name in postParams) {
			if (postParams.hasOwnProperty(name)) {
				paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
			}
		}
	}

	return paramStringPairs.join("&amp;");
};

// Public: Used to remove a SWFUpload instance from the page. This method strives to remove
// all references to the SWF, and other objects so memory is properly freed.
// Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
// Credits: Major improvements provided by steffen
SWFUpload.prototype.destroy = function () {
	try {
		// Make sure Flash is done before we try to remove it
		this.cancelUpload(null, false);
		
		// Remove the SWFUpload DOM nodes
		var movieElement = null;
		movieElement = this.getMovieElement();
		
		if (movieElement) {
			// Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround)
			for (var i in movieElement) {
				try {
					if (typeof(movieElement[i]) === "function") {
						movieElement[i] = null;
					}
				} catch (ex1) {}
			}

			// Remove the Movie Element from the page
			try {
				movieElement.parentNode.removeChild(movieElement);
			} catch (ex) {}
		}
		
		
		// Remove IE form fix reference
		window[this.movieName] = null;

		// Destroy other references
		SWFUpload.instances[this.movieName] = null;
		delete SWFUpload.instances[this.movieName];

		this.movieElement = null;
		this.settings = null;
		this.customSettings = null;
		this.eventQueue = null;
		this.movieName = null;
		
		
		return true;
	} catch (ex1) {
		return false;
	}
};

// Public: displayDebugInfo prints out settings and configuration
// information about this SWFUpload instance.
// This function (and any references to it) can be deleted when placing
// SWFUpload in production.
SWFUpload.prototype.displayDebugInfo = function () {
	this.debug(
		[
			"---SWFUpload Instance Info---\n",
			"Version: ", SWFUpload.version, "\n",
			"Movie Name: ", this.movieName, "\n",
			"Settings:\n",
			"\t", "upload_url:               ", this.settings.upload_url, "\n",
			"\t", "flash_url:                ", this.settings.flash_url, "\n",
			"\t", "use_query_string:         ", this.settings.use_query_string.toString(), "\n",
			"\t", "requeue_on_error:         ", this.settings.requeue_on_error.toString(), "\n",
			"\t", "http_success:             ", this.settings.http_success.join(", "), "\n",
			"\t", "file_post_name:           ", this.settings.file_post_name, "\n",
			"\t", "post_params:              ", this.settings.post_params.toString(), "\n",
			"\t", "file_types:               ", this.settings.file_types, "\n",
			"\t", "file_types_description:   ", this.settings.file_types_description, "\n",
			"\t", "file_size_limit:          ", this.settings.file_size_limit, "\n",
			"\t", "file_upload_limit:        ", this.settings.file_upload_limit, "\n",
			"\t", "file_queue_limit:         ", this.settings.file_queue_limit, "\n",
			"\t", "debug:                    ", this.settings.debug.toString(), "\n",

			"\t", "prevent_swf_caching:      ", this.settings.prevent_swf_caching.toString(), "\n",

			"\t", "button_placeholder_id:    ", this.settings.button_placeholder_id.toString(), "\n",
			"\t", "button_image_url:         ", this.settings.button_image_url.toString(), "\n",
			"\t", "button_width:             ", this.settings.button_width.toString(), "\n",
			"\t", "button_height:            ", this.settings.button_height.toString(), "\n",
			"\t", "button_text:              ", this.settings.button_text.toString(), "\n",
			"\t", "button_text_style:        ", this.settings.button_text_style.toString(), "\n",
			"\t", "button_text_top_padding:  ", this.settings.button_text_top_padding.toString(), "\n",
			"\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
			"\t", "button_action:            ", this.settings.button_action.toString(), "\n",
			"\t", "button_disabled:          ", this.settings.button_disabled.toString(), "\n",

			"\t", "custom_settings:          ", this.settings.custom_settings.toString(), "\n",
			"Event Handlers:\n",
			"\t", "swfupload_loaded_handler assigned:  ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
			"\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
			"\t", "file_queued_handler assigned:       ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
			"\t", "file_queue_error_handler assigned:  ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
			"\t", "upload_start_handler assigned:      ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
			"\t", "upload_progress_handler assigned:   ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
			"\t", "upload_error_handler assigned:      ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
			"\t", "upload_success_handler assigned:    ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
			"\t", "upload_complete_handler assigned:   ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
			"\t", "debug_handler assigned:             ", (typeof this.settings.debug_handler === "function").toString(), "\n"
		].join("")
	);
};

/* Note: addSetting and getSetting are no longer used by SWFUpload but are included
	the maintain v2 API compatibility
*/
// Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
SWFUpload.prototype.addSetting = function (name, value, default_value) {
    if (value == undefined) {
        return (this.settings[name] = default_value);
    } else {
        return (this.settings[name] = value);
	}
};

// Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
SWFUpload.prototype.getSetting = function (name) {
    if (this.settings[name] != undefined) {
        return this.settings[name];
	}

    return "";
};



// Private: callFlash handles function calls made to the Flash element.
// Calls are made with a setTimeout for some functions to work around
// bugs in the ExternalInterface library.
SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
	argumentArray = argumentArray || [];
	
	var movieElement = this.getMovieElement();
	var returnValue, returnString;

	// Flash's method if calling ExternalInterface methods (code adapted from MooTools).
	try {
		returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
		returnValue = eval(returnString);
	} catch (ex) {
		throw "Call to " + functionName + " failed";
	}
	
	// Unescape file post param values
	if (returnValue != undefined && typeof returnValue.post === "object") {
		returnValue = this.unescapeFilePostParams(returnValue);
	}

	return returnValue;
};


/* *****************************
	-- Flash control methods --
	Your UI should use these
	to operate SWFUpload
   ***************************** */

// WARNING: this function does not work in Flash Player 10
// Public: selectFile causes a File Selection Dialog window to appear.  This
// dialog only allows 1 file to be selected.
SWFUpload.prototype.selectFile = function () {
	this.callFlash("SelectFile");
};

// WARNING: this function does not work in Flash Player 10
// Public: selectFiles causes a File Selection Dialog window to appear/ This
// dialog allows the user to select any number of files
// Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
// If the selection name length is too long the dialog will fail in an unpredictable manner.  There is no work-around
// for this bug.
SWFUpload.prototype.selectFiles = function () {
	this.callFlash("SelectFiles");
};


// Public: startUpload starts uploading the first file in the queue unless
// the optional parameter 'fileID' specifies the ID 
SWFUpload.prototype.startUpload = function (fileID) {
	this.callFlash("StartUpload", [fileID]);
};

// Public: cancelUpload cancels any queued file.  The fileID parameter may be the file ID or index.
// If you do not specify a fileID the current uploading file or first file in the queue is cancelled.
// If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter.
SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
	if (triggerErrorEvent !== false) {
		triggerErrorEvent = true;
	}
	this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
};

// Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
// If nothing is currently uploading then nothing happens.
SWFUpload.prototype.stopUpload = function () {
	this.callFlash("StopUpload");
};

/* ************************
 * Settings methods
 *   These methods change the SWFUpload settings.
 *   SWFUpload settings should not be changed directly on the settings object
 *   since many of the settings need to be passed to Flash in order to take
 *   effect.
 * *********************** */

// Public: getStats gets the file statistics object.
SWFUpload.prototype.getStats = function () {
	return this.callFlash("GetStats");
};

// Public: setStats changes the SWFUpload statistics.  You shouldn't need to 
// change the statistics but you can.  Changing the statistics does not
// affect SWFUpload accept for the successful_uploads count which is used
// by the upload_limit setting to determine how many files the user may upload.
SWFUpload.prototype.setStats = function (statsObject) {
	this.callFlash("SetStats", [statsObject]);
};

// Public: getFile retrieves a File object by ID or Index.  If the file is
// not found then 'null' is returned.
SWFUpload.prototype.getFile = function (fileID) {
	if (typeof(fileID) === "number") {
		return this.callFlash("GetFileByIndex", [fileID]);
	} else {
		return this.callFlash("GetFile", [fileID]);
	}
};

// Public: addFileParam sets a name/value pair that will be posted with the
// file specified by the Files ID.  If the name already exists then the
// exiting value will be overwritten.
SWFUpload.prototype.addFileParam = function (fileID, name, value) {
	return this.callFlash("AddFileParam", [fileID, name, value]);
};

// Public: removeFileParam removes a previously set (by addFileParam) name/value
// pair from the specified file.
SWFUpload.prototype.removeFileParam = function (fileID, name) {
	this.callFlash("RemoveFileParam", [fileID, name]);
};

// Public: setUploadUrl changes the upload_url setting.
SWFUpload.prototype.setUploadURL = function (url) {
	this.settings.upload_url = url.toString();
	this.callFlash("SetUploadURL", [url]);
};

// Public: setPostParams changes the post_params setting
SWFUpload.prototype.setPostParams = function (paramsObject) {
	this.settings.post_params = paramsObject;
	this.callFlash("SetPostParams", [paramsObject]);
};

// Public: addPostParam adds post name/value pair.  Each name can have only one value.
SWFUpload.prototype.addPostParam = function (name, value) {
	this.settings.post_params[name] = value;
	this.callFlash("SetPostParams", [this.settings.post_params]);
};

// Public: removePostParam deletes post name/value pair.
SWFUpload.prototype.removePostParam = function (name) {
	delete this.settings.post_params[name];
	this.callFlash("SetPostParams", [this.settings.post_params]);
};

// Public: setFileTypes changes the file_types setting and the file_types_description setting
SWFUpload.prototype.setFileTypes = function (types, description) {
	this.settings.file_types = types;
	this.settings.file_types_description = description;
	this.callFlash("SetFileTypes", [types, description]);
};

// Public: setFileSizeLimit changes the file_size_limit setting
SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
	this.settings.file_size_limit = fileSizeLimit;
	this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
};

// Public: setFileUploadLimit changes the file_upload_limit setting
SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
	this.settings.file_upload_limit = fileUploadLimit;
	this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
};

// Public: setFileQueueLimit changes the file_queue_limit setting
SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
	this.settings.file_queue_limit = fileQueueLimit;
	this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
};

// Public: setFilePostName changes the file_post_name setting
SWFUpload.prototype.setFilePostName = function (filePostName) {
	this.settings.file_post_name = filePostName;
	this.callFlash("SetFilePostName", [filePostName]);
};

// Public: setUseQueryString changes the use_query_string setting
SWFUpload.prototype.setUseQueryString = function (useQueryString) {
	this.settings.use_query_string = useQueryString;
	this.callFlash("SetUseQueryString", [useQueryString]);
};

// Public: setRequeueOnError changes the requeue_on_error setting
SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
	this.settings.requeue_on_error = requeueOnError;
	this.callFlash("SetRequeueOnError", [requeueOnError]);
};

// Public: setHTTPSuccess changes the http_success setting
SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
	if (typeof http_status_codes === "string") {
		http_status_codes = http_status_codes.replace(" ", "").split(",");
	}
	
	this.settings.http_success = http_status_codes;
	this.callFlash("SetHTTPSuccess", [http_status_codes]);
};


// Public: setDebugEnabled changes the debug_enabled setting
SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
	this.settings.debug_enabled = debugEnabled;
	this.callFlash("SetDebugEnabled", [debugEnabled]);
};

// Public: setButtonImageURL loads a button image sprite
SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
	if (buttonImageURL == undefined) {
		buttonImageURL = "";
	}
	
	this.settings.button_image_url = buttonImageURL;
	this.callFlash("SetButtonImageURL", [buttonImageURL]);
};

// Public: setButtonDimensions resizes the Flash Movie and button
SWFUpload.prototype.setButtonDimensions = function (width, height) {
	this.settings.button_width = width;
	this.settings.button_height = height;
	
	var movie = this.getMovieElement();
	if (movie != undefined) {
		movie.style.width = width + "px";
		movie.style.height = height + "px";
	}
	
	this.callFlash("SetButtonDimensions", [width, height]);
};
// Public: setButtonText Changes the text overlaid on the button
SWFUpload.prototype.setButtonText = function (html) {
	this.settings.button_text = html;
	this.callFlash("SetButtonText", [html]);
};
// Public: setButtonTextPadding changes the top and left padding of the text overlay
SWFUpload.prototype.setButtonTextPadding = function (left, top) {
	this.settings.button_text_top_padding = top;
	this.settings.button_text_left_padding = left;
	this.callFlash("SetButtonTextPadding", [left, top]);
};

// Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
SWFUpload.prototype.setButtonTextStyle = function (css) {
	this.settings.button_text_style = css;
	this.callFlash("SetButtonTextStyle", [css]);
};
// Public: setButtonDisabled disables/enables the button
SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
	this.settings.button_disabled = isDisabled;
	this.callFlash("SetButtonDisabled", [isDisabled]);
};
// Public: setButtonAction sets the action that occurs when the button is clicked
SWFUpload.prototype.setButtonAction = function (buttonAction) {
	this.settings.button_action = buttonAction;
	this.callFlash("SetButtonAction", [buttonAction]);
};

// Public: setButtonCursor changes the mouse cursor displayed when hovering over the button
SWFUpload.prototype.setButtonCursor = function (cursor) {
	this.settings.button_cursor = cursor;
	this.callFlash("SetButtonCursor", [cursor]);
};

/* *******************************
	Flash Event Interfaces
	These functions are used by Flash to trigger the various
	events.
	
	All these functions a Private.
	
	Because the ExternalInterface library is buggy the event calls
	are added to a queue and the queue then executed by a setTimeout.
	This ensures that events are executed in a determinate order and that
	the ExternalInterface bugs are avoided.
******************************* */

SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
	// Warning: Don't call this.debug inside here or you'll create an infinite loop
	
	if (argumentArray == undefined) {
		argumentArray = [];
	} else if (!(argumentArray instanceof Array)) {
		argumentArray = [argumentArray];
	}
	
	var self = this;
	if (typeof this.settings[handlerName] === "function") {
		// Queue the event
		this.eventQueue.push(function () {
			this.settings[handlerName].apply(this, argumentArray);
		});
		
		// Execute the next queued event
		setTimeout(function () {
			self.executeNextEvent();
		}, 0);
		
	} else if (this.settings[handlerName] !== null) {
		throw "Event handler " + handlerName + " is unknown or is not a function";
	}
};

// Private: Causes the next event in the queue to be executed.  Since events are queued using a setTimeout
// we must queue them in order to garentee that they are executed in order.
SWFUpload.prototype.executeNextEvent = function () {
	// Warning: Don't call this.debug inside here or you'll create an infinite loop

	var  f = this.eventQueue ? this.eventQueue.shift() : null;
	if (typeof(f) === "function") {
		f.apply(this);
	}
};

// Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
// properties that contain characters that are not valid for JavaScript identifiers. To work around this
// the Flash Component escapes the parameter names and we must unescape again before passing them along.
SWFUpload.prototype.unescapeFilePostParams = function (file) {
	var reg = /[$]([0-9a-f]{4})/i;
	var unescapedPost = {};
	var uk;

	if (file != undefined) {
		for (var k in file.post) {
			if (file.post.hasOwnProperty(k)) {
				uk = k;
				var match;
				while ((match = reg.exec(uk)) !== null) {
					uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
				}
				unescapedPost[uk] = file.post[k];
			}
		}

		file.post = unescapedPost;
	}

	return file;
};

SWFUpload.prototype.flashReady = function () {
	// Check that the movie element is loaded correctly with its ExternalInterface methods defined
	var movieElement = this.getMovieElement();

	// Pro-actively unhook all the Flash functions
	if (typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
		this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
		for (var key in movieElement) {
			try {
				if (typeof(movieElement[key]) === "function") {
					movieElement[key] = null;
				}
			} catch (ex) {
			}
		}
	}
	
	this.queueEvent("swfupload_loaded_handler");
};


/* This is a chance to do something before the browse window opens */
SWFUpload.prototype.fileDialogStart = function () {
	this.queueEvent("file_dialog_start_handler");
};


/* Called when a file is successfully added to the queue. */
SWFUpload.prototype.fileQueued = function (file) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("file_queued_handler", file);
};


/* Handle errors that occur when an attempt to queue a file fails. */
SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
};

/* Called after the file dialog has closed and the selected files have been queued.
	You could call startUpload here if you want the queued files to begin uploading immediately. */
SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued) {
	this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued]);
};

SWFUpload.prototype.uploadStart = function (file) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("return_upload_start_handler", file);
};

SWFUpload.prototype.returnUploadStart = function (file) {
	var returnValue;
	if (typeof this.settings.upload_start_handler === "function") {
		file = this.unescapeFilePostParams(file);
		returnValue = this.settings.upload_start_handler.call(this, file);
	} else if (this.settings.upload_start_handler != undefined) {
		throw "upload_start_handler must be a function";
	}

	// Convert undefined to true so if nothing is returned from the upload_start_handler it is
	// interpretted as 'true'.
	if (returnValue === undefined) {
		returnValue = true;
	}
	
	returnValue = !!returnValue;
	
	this.callFlash("ReturnUploadStart", [returnValue]);
};



SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
};

SWFUpload.prototype.uploadError = function (file, errorCode, message) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_error_handler", [file, errorCode, message]);
};

SWFUpload.prototype.uploadSuccess = function (file, serverData) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_success_handler", [file, serverData]);
};

SWFUpload.prototype.uploadComplete = function (file) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_complete_handler", file);
};

/* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
   internal debug console.  You can override this event and have messages written where you want. */
SWFUpload.prototype.debug = function (message) {
	this.queueEvent("debug_handler", message);
};


/* **********************************
	Debug Console
	The debug console is a self contained, in page location
	for debug message to be sent.  The Debug Console adds
	itself to the body if necessary.

	The console is automatically scrolled as messages appear.
	
	If you are using your own debug handler or when you deploy to production and
	have debug disabled you can remove these functions to reduce the file size
	and complexity.
********************************** */
   
// Private: debugMessage is the default debug_handler.  If you want to print debug messages
// call the debug() function.  When overriding the function your own function should
// check to see if the debug setting is true before outputting debug information.
SWFUpload.prototype.debugMessage = function (message) {
	if (this.settings.debug) {
		var exceptionMessage, exceptionValues = [];

		// Check for an exception object and print it nicely
		if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
			for (var key in message) {
				if (message.hasOwnProperty(key)) {
					exceptionValues.push(key + ": " + message[key]);
				}
			}
			exceptionMessage = exceptionValues.join("\n") || "";
			exceptionValues = exceptionMessage.split("\n");
			exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
			SWFUpload.Console.writeLine(exceptionMessage);
		} else {
			SWFUpload.Console.writeLine(message);
		}
	}
};

SWFUpload.Console = {};
SWFUpload.Console.writeLine = function (message) {
	var console, documentForm;

	try {
		console = document.getElementById("SWFUpload_Console");

		if (!console) {
			documentForm = document.createElement("form");
			document.getElementsByTagName("body")[0].appendChild(documentForm);

			console = document.createElement("textarea");
			console.id = "SWFUpload_Console";
			console.style.fontFamily = "monospace";
			console.setAttribute("wrap", "off");
			console.wrap = "off";
			console.style.overflow = "auto";
			console.style.width = "700px";
			console.style.height = "350px";
			console.style.margin = "5px";
			documentForm.appendChild(console);
		}

		console.value += message + "\n";

		console.scrollTop = console.scrollHeight - console.clientHeight;
	} catch (ex) {
		alert("Exception: " + ex.name + " Message: " + ex.message);
	}
};


/*
  Scroll to any node on page.

  Usage:
    1. add class "j-scrollto j-scrollto-UID" to link
    2. add id "anchor-UID" to element where page must be positioned
*/


(function( $ ){
  
  $(document).ready(function(){
    $(".j-scrollto").click(function(){
      try{
        var $this = $(this);
        var uid = $this.attr("class").match(/j-scrollto-([^ ]+)/);
        if(uid[1]){
          uid = uid[1];
          var scrollTo = $("#anchor-" + uid);
          if(scrollTo.length > 0){
            $.scrollTo(scrollTo, { offset: -40, duration: 400, easing: "easeOutExpo" });
            return false;
          }
        }
      }
      catch(e){
        
      }
    });
  })
  
})( jQuery );
/*
 *
 */
jQuery(document).ready(function() {
	if(current_user_id) {
		jQuery('.j-cache-link').each(function() {
			var link = jQuery(this);
			link.attr('href', link.attr('href').replace(/login/, current_user_login).replace(/\/cache/, ''));
		})
	};
});
jQuery(document).ready(function() {
	if (!current_user_id)
	  jQuery('.j-cache-hide-from-anonymous').hide();	
});

jQuery(document).ready(function() {
	jQuery('.j-cache-expert-comments').each(function() {
		var comment = jQuery(this);
		
		if (parseInt(comment.find('.j-cache-expert-comments-count').text()) > 0)
			comment.show();
	});	
});
/*
* Актуализация кешированной информации – обновление информации в кешированном HTML.
* */
function update_cached_attributes(hashed_resources){
  for (var i=0; i < hashed_resources.length; i++) {
    var resource = hashed_resources[i];
    var updating = jQuery('#' + resource.id);

    for (attribute in resource){

      if(attribute != 'id'){
        /* В классах разделителем слов служит черточка, а в базе - подчеркивание */
        updating.find(".j-cache-" + attribute.replace(/_/g, "-")).html(resource[attribute]);
      }

      if(resource.expert_comments_count && resource.expert_comments_count > 0){
          updating.find('.j-cache-expert-comments').show();
      }
    }
  }
}
/*
 * Отследить событие в сборщиках статистики
 * Аргументы:
 *  category
 *  action
 *  label (optional)
 *  value (optional integer)
 */
function track_event(){
  if (typeof(pageTracker) != "undefined"){
    //pageTracker._trackEvent.apply(window, arguments);
  }
}
/* Ссылка добавления в избранное */

(function( $ ){

  this.FavesLink = {
    /* state: true (когда добавлено), false (когда удалено) */
    update_state: function(state, dom_id){
      var link_block = jQuery('#' + dom_id);
      var add_link = link_block.find('.j-faves-add');
      var remove_link = link_block.find('.j-faves-remove');
      if(state){
        add_link.hide(); remove_link.show();
      }else{
        add_link.show(); remove_link.hide();
      }
    }
  }

})( jQuery );
/* Button object */

(function($) {

  var buttons = new Array();

  this.b_button_OPTIONS = {
    selfInit: false,
    defaultName: "button",
    className: "b-button",
    formClass: "b-button_form",
    template:
      '<div class="b-button" bindEvents="mousedown,mouseup,mouseover,mouseout">' +
        '<table><tr><td>' +
          '<div class="b-button-bg">' +
            '<i class="l g-png"></i><i class="r g-png"></i>' +
          '</div>' +
          '<div class="b-button-text" attachData="value">' +
            '<i class="b-button-icon g-png"></i>' +
          '</div>' +
        '</td></tr></table>' +
      '</div>'
  };

  this.b_button_IDs = 0;

  if(b_button_OPTIONS.selfInit){
    //Self-init:
    $(document).ready(function(){
      GLOBAL.reInit(function(){
        b_button_init();
      })
    })
  }

  // Force init:
  this.b_button_init = function(str){
    if(str){
      var obj = document.getElementById(str);
      if(obj){
        var jobj = $(obj);
        if(jobj.find(".b-button_form").length)
          new b_button_group(obj);
        else
          new b_button(obj);
      } 
    } else {

      $("*[buttonType=group]").each(function(){
        new b_button_group(this);
      })
      $("button[buttonType]").each(function(){
        new b_button(this);
      })

    }
  }

  
  this.b_button = function(){
    return this.init.apply(this, arguments);
  }

  b_button.prototype = {
    init: function(obj, options){
      this.options = $.extend(b_button_OPTIONS, options ? options : {});

      this.domNode = $(obj);
      
      var b = this.isExist();
      if(b){ return b; }

      this.is = {
        prevent: true,
        stateBubble: true,
        template: false
      };

      if(this.domNode.find("." + this.options.className).length)
        this.is.template = true;
        
      this.old = {} // save here old states if it changes

      this.o = {
        type: this.domNode.attr("buttonType"),
        confirm: this.domNode.attr("confirm")
      };

      this.checked = false;
      this.name = this.domNode.attr("name") ? this.domNode.attr("name") : this.options.defaultName + b_button_IDs++;

      // events for append
      this.e = {
        list: ["mousedown", "mouseup", "mouseover", "mouseout"],
        onstatechange: this.domNode.attr("onstatechange") ? this.domNode.attr("onstatechange") : function(){}
      };
      

      if(!this.is.template){

        this.value = this.domNode.html();
        
        // data for append
        this.d = {
          value: this.value
        }

        var checkedLabel = this.domNode.attr("checkedLabel");
        if(checkedLabel && checkedLabel.length){
          this.d.value = '' +
            '<span class="off">' + this.value + '</span>' +
            '<span class="on">' + checkedLabel + '</span>'
        }

        this.domNode
          .removeAttr("buttonType")
          .addClass(this.options.formClass)
          .html(this.parse(this.options.template)) // parse nodes and append events and data

      } else {
        this.parse(this.domNode);
      }
      
      this.bindEvents();
        
      if(this.domNode.get(0).disabled) // define disabled state
        this.setClass(this.domNode, "disabled") 

      var checked = this.domNode.attr("checked");
      if(checked && (checked == 'true' || checked == 'checked') && this.o.type != "simple"){ // define checked state
        this.is.stateBubble = false;
        this.state("checked", true, true)
      }
      
      this.postCreate();

      obj.buttonHandler = this;
      buttons.push(this);
    },
    
    isExist: function(){
      for (var i=0; i < buttons.length; i++) {
        if(buttons[i].domNode.get(0) == this.domNode.get(0))
          return buttons[i];
      };
      return false;
    },
    
    postCreate: function(){

      var _on = this.domNode.find(".on");
      var _off = this.domNode.find(".off");
      var w = {
        on: _on.css({ display: "inline-block" }).width()+1,
        off: _off.css({ display: "inline-block" }).width()+1
      }
      _on.removeAttr("style");
      _off.removeAttr("style");

      if(w.on >= w.off){
        _on.css({ width: w.on });
        _off.css({ width: w.on });
      } else {
        _on.css({ width: w.off });
        _off.css({ width: w.off });
      }

    },
    
    bindEvents: function(){
      var $this = this;

      for (var i=0; i < this.e.list.length; i++) {
        var _event = this.e.list[i];
        if(this[_event]){
          
          (function(_event){
            $this.domNode.bind(_event, function(){
              $this[_event].apply($this, $this.e[_event] ? [$this.e[_event]] : null)
            });

            if(_event == 'mouseup')
              $(document).bind(_event, function(){
                $this[_event].apply($this, $this.e[_event] ? [$this.e[_event]] : null)
              })

          })(_event)

        }
      };

    },
    
    mousedown: function(node){
      var node = node ? node : this.domNode;

      switch(this.o.type){
        case 'trigger':
          if(this.checked){
            this.is.prevent = false;
          } else {
            this.state("checked", true);
            this.is.prevent = true;
          }
          break;

        case 'switcher':
          if(!this.checked)
            this.state("checked", true);
          
          break;

        case 'simple':
        default:
          this.is.prevent = false;
          this.setClass(node, "down");
          break;
      }

    },

    mouseup: function(node){
      var node = node ? node : this.domNode;

      if(!this.is.prevent){
        switch(this.o.type){
          case 'trigger':
            if(this.checked) this.state("checked", false);
            break;

          case 'trigger':
            
            break;

          case 'simple':
          default:
            this.setClass(node, "down", false);
            break
        }
      }

    },

    mouseover: function(node){
      var node = node ? node : this.domNode;
      this.setClass(node, "hover");
    },

    mouseout: function(node){
      var node = node ? node : this.domNode;
      this.setClass(node, "hover", false);
    },
    
    onstatechange: function(){
    },
    
    _onstatechange: function(){
      this.onstatechange.apply(this);
      if($.isFunction(this.e.onstatechange))
        this.e.onstatechange.apply(this)
      else
        eval(this.e.onstatechange)
    },
    
    parse: function(tpl){

      function bind( dom ){
        dom.filter("[bindEvents]").add(dom.find("*[bindEvents]")).each(function(){
          var node = $(this);
          jQuery.each(node.attr("bindEvents").split(/ *, */), function(){
            var _event = this.toString();
            $this.e[_event] = node;
          });
          node.removeAttr("bindEvents");
        })
      }
      
      function append( dom ){
        dom.filter("[attachData]").add(dom.find("*[attachData]")).each(function(){
          var node = $(this);
          jQuery.each(node.attr("attachData").split(/ *, */), function(){
            var _type = this.toString();
            node.append($this.d[_type]);
            $this.o[_type] = node;
          });
          $(this).removeAttr("attachData");
        })
      }

      var $this = this;

      switch(typeof tpl){

        case 'string':
          var tpl = $(tpl);
          bind(tpl);
          append(tpl);
          break;
          
        case 'object':
          bind(tpl);
          break;
      }

      return tpl;
    },
    
    setClass: function(node, sClass, b){
      if(b === false) node.removeClass(this.options.className + "_" + sClass);
      else node.addClass(this.options.className + "_" + sClass);
    },
    
    state: function(name, value, force){
      this.is.prevent = true;

      switch(name){
        case 'checked':
          if(force || !this.o.confirm || (this.o.confirm && confirm(this.o.confirm))){
            this.old[name] = this[name];
            this[name] = value;

            if(this.old[name] != this[name] && this.is.stateBubble)
              this._onstatechange()
            if(!this.is.stateBubble)
              this.is.stateBubble = true;

            if(!value)
              this.setClass(this.e.mouseup, "down", false);
            else
              this.setClass(this.e.mouseup, "down");
          }
          break;

        case 'disabled':

          this.old[name] = this[name];
          this[name] = value;

          if(value){
            this.setClass(this.domNode, name)
            this.domNode.attr(name, true)
          } else {
            this.setClass(this.domNode, name, false)
            this.domNode.removeAttr(name)
          }

          break;
      }
    }
    
    
  }

  function b_button_group(){
  	return this.init.apply(this, arguments);
  }

  b_button_group.prototype = {
    init: function(obj){
      var $this = this;
      
      this.domNode = $(obj);
      this.is = {
        template: false
      }

      if(this.domNode.find("."+ b_button_OPTIONS.className +"_left, ."+ b_button_OPTIONS.className +"_center, ."+ b_button_OPTIONS.className +"_right").length)
        this.is.template = true;

      this.e = {
        onstatechange: this.domNode.attr("onstatechange") ? this.domNode.attr("onstatechange") : function(){}
      };

      this.buttons = new Array();

      if(!this.is.template){
        var buttons = this.domNode.addClass(b_button_OPTIONS.className + "_group").find("button[buttonType]");
        
        buttons.each(function(i){
          var button = new b_button(this);
          var sClass = "center";
          if(i == 0) sClass = "left";
          if(i == buttons.length - 1) sClass = "right";

          if(buttons.length != 1)
            button.domNode.wrap($("<div>").addClass(b_button_OPTIONS.className + "_" + sClass))

          $this.buttons.push(button);
        })

      } else {
        this.domNode.find("."+ b_button_OPTIONS.className +"_form").each(function(){
          $this.buttons.push(this.buttonHandler);
        })
      }


      
      if(this.buttons.length != 1)
        this.bindEvents();
    },
    
    bindEvents: function(){
      $this = this;
      $.each(this.buttons, function(){
        this.onstatechange = function(){
          $this.onclick(this)
        };
      })
    },
    
    onclick: function(obj){
      var $this = this;

      state = {};
      state[obj.name] = true;
      state.new_state = obj.name;

      $.each(this.buttons, function(){
        if(this != obj){
          this.is.stateBubble = false;
          this.state("checked", false);
          if(this.old.checked == true && this.checked == false) {
            state[this.name] = false;
            state.old_state = this.name;
          }
        }
      })
      obj.is.prevent = true;
      

      if($.isFunction(this.e.onstatechange))
        this.e.onstatechange.apply(this)
      else
        (function(state){
          eval($this.e.onstatechange)
        }).call(obj, state)
      
    }
    
  };

})(jQuery);

/* Button object (end) */

/**************************************************
	Class:  Pretty Search
	Author: Egor Hmelyoff (hmelyoff@gmail.com)
	TODO:
		— allow safari to use own input[type=search]
		— find and return object if exist
	
**************************************************/
/*global document, jQuery */


(function( $ ) {

  var OPTIONS = {
    className: "b-search",
    template: tmpl(
      '<div class="<%=className%>">' +
  			'<div class="<%=className%>_left g-png"></div>' +
  			'<div class="<%=className%>_container">' +
  			  '<div class="<%=className%>_right g-png"></div>' + 
  			  '<div class="<%=className%>_container">' +
  					'<span class="<%=className%>_placeholder"><%=params.placeholder%></span>' +
  					'<input type="text" name="<%=params.name%>" value="<%=params.value%>" class="<%=className%>_input <%=params.className%>" results="<%=params.results%>" autocomplete="<%=params.autocomplete%>" <%=params.id%> />' +
  					'<span class="<%=className%>_spinner"></span>' +
  					'<span class="<%=className%>_clear"></span>' +
  				'</div>'+
  			'</div>'+
      '</div>'
      
    )
  };

  jQuery(document).ready(function(){
		jQuery("input[prettysearch=yes]").each(function(){
		  new classSearch(this);
		});
  });
  
  this.classSearch = _Class.extend({
    init: function( node, options ){
  		this.is = {
  			input: false
  		};

  		this.domNode = $(node);
  		node.searchHandler = this;
  		
  		this.options = $.extend(true, {}, OPTIONS, options ? options : {});
		  this.options.params = {
		    width: this.domNode.width()-13
		  };
  		
  		if( this.domNode.is("input") ){
  		  // create node by template
  		  $.extend(this.options.params, {
  		    // attrs
          id: this.domNode.attr("id") ? ('id="' + this.domNode.attr("id") + '"') : '',
  		    className: this.domNode.attr("class"),
  		    placeholder: this.domNode.attr("placeholder") ? this.domNode.attr("placeholder") : '',
          results: this.domNode.attr("results") ? this.domNode.attr("results") : 0,
          autocomplete: this.domNode.attr("autocomplete") ? this.domNode.attr("autocomplete") : 'on',
  		    incremental: this.domNode.attr("incremental") ? this.domNode.attr("incremental") : 'no',
          onsearch: this.domNode.attr("onsearch") ? this.domNode.attr("onsearch") : function(){},
          
          // form
          name: this.domNode.attr("name") ? this.domNode.attr("name") : 'q',
          value: this.domNode.attr("value") ? thid.domNode.attr("value") : ''
  		  })
  		  
  		  var template = $(this.options.template( this.options ));
        template.find( "." + this.options.className +"_container input" ).css({ outlineWidth: 0 });
  		  this.domNode.replaceWith(template);
  		  this.domNode = template;
  		  
  		} else if(this.domNode.is("." + this.options.className)) {
  		  // init already templated node
  		  var input = this.domNode.find("." + this.options.className + "_input");
  		  
  		  $.extend(this.options.params, {
  		    placeholder: this.domNode.find("." + this.options.className + "_placeholder").html(),
  		    incremental: input.attr("incremental") ? input.attr("incremental") : 'no',
          onsearch: input.attr("onsearch") ? input.attr("onsearch") : function(){},
          value: input.attr("value") ? input.attr("value") : ''
  		  })
  		  
        input.css({ outlineWidth: 0 });

  		} else {
  		  // wtf? stop here
  		  return false;
  		}


      // continue init by data

      if(!this.options.params.value && this.options.params.placeholder) {
        this.placeholder(true);
      }
       
      if(this.options.params.value) {
        this.clear(true);
      }
      
      this._events();
  		
    },
    
    _events: function(){
      var self = this;
      var input = this.domNode.find("." + this.options.className + "_input");

      this.domNode
        .mousedown(function(){
          self.placeholder(false);
          self.domNode.addDependClass("focus");

          if(!self.is.input) return false;
          else self.is.input = false;
        })
        .mouseup(function(){
          input.focus();
        });
      
      input
        .focus(function(){
          self.domNode.addDependClass("focus");
          self.placeholder(false);
        })
        .blur(function(){
          self.domNode.removeDependClass("focus");
          if(!input.val()) self.placeholder(true);
        })
        .keyup(function(){
          if(input.val())
            self.clear(true);
          else
            self.clear(false);

          self.value = input.val();
          if(self.options.params.incremental == 'yes') {
            self.onsearch();
          }
        })
        .mousedown(function(){
          self.is.input = true;
        })
        .change(function(){
          self.value = input.val();
          if(self.options.params.incremental == 'yes') {
            self.onsearch();
          }
        })
        .parents("form").submit(function(){
          self.onsubmit();
        });

      this.domNode.find("." + this.options.className + "_clear")
        .mousedown(function(){
          $(this).addDependClass("down", "_");
          input.focus().select();
          return false;
        })
        .click(function(){
          self.value = input.val("").focus().val();
          $(this).removeDependClass("down", "_").hide();
          if(self.options.params.incremental == 'yes') {
            self.onsearch();
          }
        });

      this.onsearch = function(){
        if($.isFunction(this.options.params.onsearch)) {
          this.options.params.onsearch.apply(self);
        } else {
          eval(this.options.params.onsearch);
        }
      };

      this.events();

    },

    events: function(){ },

    onsearch: function(){ },

    onsubmit: function(){
      this.onsearch();
    },
    
    placeholder: function( b ){
      var p = this.domNode.find("." + this.options.className + "_placeholder");
      if( b ) p.show();
      else    p.hide();
    },

    clear: function( b ){
      var p = this.domNode.find("." + this.options.className + "_clear");
      if( b ) p.show();
      else    p.hide();
    },

    loading: function( b ){
      if( b )
        this.domNode.addDependClass("loading");
      else
        this.domNode.removeDependClass("loading");
    }
    
    
  });

})( jQuery );

/* Button object */

var b_notice_OPTIONS = {
  template:
    '<span class="b-notice">' +
      '<i class="icon"></i>' +
      '<span class="b-notice-animate">' +
        '<span class="hide">cacher</span>' +
        '<span class="b-notice-text"></span>' +
      '</span>' +
    '</span>',
    
  selectorHTML: ".b-notice-text",
  selectorAnimate: ".b-notice-animate",
  selectorEventShow: "i.icon",
  selectorEventHide: ".hide"
};

(function($) {
  
  $(document).ready(function(){
    $(".b-notice").not(".b-notice_show").each(function(){
      new b_notice(this)
    })
  })

  function b_notice(){
  	return this.init.apply(this, arguments);
  }

  b_notice.prototype = {
    init: function(obj, options){
      this.options = $.extend(b_notice_OPTIONS, options ? options : {});
      
      this.is = {
        display: false,
        animate: false
      }

      this.domNode = $(obj);
      this.className = this.domNode.attr("class");
      this.html = this.domNode.html();
      
      var domNode = $(this.options.template)
        .addClass(this.className);

      domNode.find(this.options.selectorHTML).html(this.html);
        
      this.domNode.replaceWith(domNode);
      this.domNode = domNode;

      this.bindEvents();

      domNode.show();
      
    },
    
    bindEvents: function(){
      var $this = this;
      this.domNode.find(this.options.selectorEventShow)
        .click(function(){
          if(!$this.is.animate){
            var node = $this.domNode.find($this.options.selectorAnimate);

            if($this.is.display){
              hide(node)
            } else {
              show(node);
            }
          }
        })

      this.domNode.find(this.options.selectorEventHide)
        .click(function(){
          if(!$this.is.animate)
            hide($this.domNode.find($this.options.selectorAnimate));
        })
        
      var show = function(node){
        $this.is.display = true;
        $this.is.animate = true;

        var h = node.css({ display: "block" }).height();
        node.hide();
        
        node.css({ height: 0, overflow: "hidden", position: "relative", opacity: 0 })
          .animate({ height: h, opacity: 1 }, function(){
            $this.is.animate = false;
          })
      }
      
      var hide = function(node){
        $this.is.display = false;
        $this.is.animate = true;
        node
          .animate({ height: 0, opacity: 0 }, function(){
            $(this).removeAttr("style");
            $this.is.animate = false;
          })
      }
    }
    
  };

})(jQuery);

/* Button object (end) */

/*
  Bubble plugin.
  Written by Egor Hmelyoff (hmelyoff@gmail.com)
  
  Global object:
    bubble
  
  Api:
    bubble.show(@data, @settings) — show bubble

    bubble.close(@settings) — close bubble

    bubble.append(node, @settings) — append data to bubble
      — return: uid:Number to show bubble later
      
    bubble.onload(func:Function) — execute func after bubble loading
    
  Params:
    @data:
      — "remote:url/page"  :String     — load page by ajax
      — "image:url/image]" :String     — preload and show any image
      — "html data string" :String     — create object from html data and show bubble with it (not working now)
      — "any text"         :String     — show bubble with this text (not working now)
    
      — uid                :Number     — show node generated by bubble.append

      — node               :DOM/Object — append node and show it
        
    @settings:Object
      — from               :DOM/Object — animate bubble from this node/size object (undefined — show from center or current state)
        { width: px, height: px, left: px, top: px }

      — to                 :DOM/Object — animate bubble to this node/size object (undefined — show to center, normal mode)
        { width: px, height: px, left: px, top: px }

      — message            :String     — Preload message
      — success            :Boolean    — Set preload icon to success

      — event              :Event      — to be able catch users pressed keys and so on (now using for make animation slower with Alt key)
      — reload             :Boolean    — if true reload ajax data for each "remote" bubble show
      — serialize          :FROM_ID    — ID of form to serialize and send with "remote" request
      — ajax               :Object     — object to extend ajax request object (look jQuery.ajax) (not working now)

      — oncreate(@node)    :Function   — call after data append by bubble.append in bubble context
      — onclose()          :Function   — call after bubble closed
  
  Example:
    bubble.show("remote:/login", { event: event, from: this })
    
  TODO:
    — centering content over animation
    — finishing list above
    — initialize bubble on show if it still does not initialized

*/

(function($) {
  
  var onload = [];
  var $this = this;

  this.bubble = {};
  this.bubble.onload = function(func){
    onload.push(func);
  }

  $(window).load(function(){
    $this.bubble = new b_bubble();
    bubble.postCreate();
  })
  
  var b_bubble_OPTIONS = {
    className: "b-bubble",
    classFixed: "b-bubble-fixed",

    opacityUnderLayer: 0.3,

    speed: 400, //ms
    speedSlow: 4000, //ms
    
    shadowSize: 43,
    alwaysOnTop: true,

    animation: "swing",
    animationClose: "easeInBack",
    
    preload: {
      width: 250,
      height: 150
    },
    
    template: 
  		'<div>' +
  			'<div class="b_c">' +
  				'<div class="b_t"><div><div></div></div></div>' +
  				'<div class="b_r"><div><div></div></div></div>' +
  				'<div class="b_b"><div><div></div></div></div>' +
  				'<div class="b_l"><div><div></div></div></div>' +
  				'<div class="b_content_out">' +
			      '<div class="b_close" title="Esc"></div>'+
  					'<div class="b_content">' +
  					'</div>' +
  				'</div>' +
  			'</div>' +
  		'</div>'
  }

  this.b_bubble = function(){
  	return this.init.apply(this, arguments);
  }
  
  b_bubble.prototype = {
    init: function(options){
      this.options = $.extend(b_bubble_OPTIONS, options ? options : {});
      
      this.is = {
        created: false,
        opened: false,
        closing: false,
        animate: false,
        loading: false
      }
      
      this.queue = [];
      this.cache = [];
      this.events = [];
      
      this.create();
    },
    create: function(){
      if(!this.is.created){

        this.ptr = $(this.options.template)
          .css({ left: -9999, top: -9999 })
          .addClass(this.options.className)

        this.ptr.prependTo(document.body);

        this.o = {
          content: this.ptr.find(".b_content"),
          close: this.ptr.find(".b_close"),
          bc: this.ptr.find(".b_c"),
    			eh: this.ptr.find(".b_t div").height(),
    			ew: this.ptr.find(".b_l div").width(),
            
    			oh: this.ptr.find(".b_t, .b_b"),
    			ot: this.ptr.find(".b_r div div, .b_l"),
    			ob: this.ptr.find(".b_r div, .b_l div").not(".b_r div div, .b_l div div"),
            
    			ow: this.ptr.find(".b_r, .b_l"),
    			or: this.ptr.find(".b_t div, .b_b div").not(".b_t div div, .b_b div div"),
    			ol: this.ptr.find(".b_t div div, .b_b")
        }
        this.o.pt = parseInt(this.o.bc.css("padding-top"));
  			this.o.pl = parseInt(this.o.bc.css("padding-left"));
  			
  			//this.ptr.hide();

        if($.browser.msie && $.browser.version < 7)
          this.ptr.wrap($("<div>").addClass(this.options.classFixed).hide())

  			this.underLayer = $("<div>").addClass("b-bubble-under").hide();
  			this.underLayer.insertAfter(this.ptr);

  			
  			var $this = this;
  			this.o.close.add(this.underLayer).click(function(evt){
  			  $this.close({ event: evt });
  			})
  			
  			$(document).keypress(function( event ){
  			  if(event.keyCode == 27 && $this.is.opened){
  			    $this.close({ event: event });
  			    return false;
  			  }
  			})
  			
  			
  			
        this.is.created = true;
      }
    },
    
    onload: function(func){
      if($.isFunction(func))
        func.call(window);
    },
    postCreate: function(){
			if(onload.length){
			  for (var i=0; i < onload.length; i++) {
			    if($.isFunction(onload[i]))
			      onload[i].call(window);
			  };
			  onload = [];
			}
    },


    
    addQueue: function(func){
      if(!this.queueCount)
        this.queueCount = 0;
        
      this.queue.push(func);
      this.queueCount++;
      this.check();
    },
    check: function(){
      if(!this.is.animate && this.queue.length){
        this.queue[0].call(this);
        this.queue.shift();
      }
    },
    inCache: function(data){
      for (var i=0; i < this.cache.length; i++) {
        if(this.cache[i].uid && this.cache[i].uid == data)
          return this.cache[i];

        if(this.cache[i].src && this.cache[i].src == data)
          return this.cache[i];

        if(this.cache[i].url && this.cache[i].url == data)
          return this.cache[i];

        if(this.cache[i].node && this.cache[i].node == data)
          return this.cache[i];
      };
      return false;
    },
    cleanCache: function(cache){
      for (var i=0; i < this.cache.length; i++) {
        if(this.cache[i] == cache)
          break;
      }
      this.cache.splice(i, 1);
    },


    animate: function(settings){
      var $this = this;

      if(!this.is.animate){
        this.is.animate = true;
        
        if(!this.is.opened)
          this.ptr.css({ left: -9999, top: -9999 }).show();
        
        if(this.is.opened)
          settings.from = null;

        from = this.normalize(settings.from);
        if(this.is.opened){
          $.extend(from, { width: this.sizes.w, height: this.sizes.h })
        }

  			this.sizes = {
  				w: from.width,
  				h: from.height,
  				l: from.left,
  				t: from.top
  			}

  			this.o.content.css({
  				width: Math.round(this.sizes.w),
  				height: Math.round(this.sizes.h)
  			});

				var top = from.top - this.ptr.height()/2;
				if(this.options.alwaysOnTop && this.options.shadowSize)
  				if(top < -this.options.shadowSize) top = -this.options.shadowSize;

  			this.ptr.css({
  				left: from.left - this.ptr.width()/2,
  				top: top
  			})
  			
  			if(!$.browser.msie && !this.is.opened)
  			  this.ptr.css({ opacity: 0 })

  			this.setLimit();

        to = this.normalize(settings.to);
		    this.o.content.css({ overflowY: "hidden" });
        
        this.underLayer.css({ opacity: this.options.opacityUnderLayer }).show();

        var speed = this.options.speed;
        try{
          if(settings.event && settings.event.altKey === true)
            speed = this.options.speedSlow;
        } catch(e){}
          

        var animation = this.options.animation;
        if(this.is.closing)
          animation = this.options.animationClose;
          
  			this.oAni = new classAnimate(function(now, prev){
  				$this.sizes = {
  					w: $this.sizes.w + ((to.width-from.width)*(now-prev)),
  					h: $this.sizes.h + ((to.height-from.height)*(now-prev))
  				}

  				$this.o.content.css({
  					width: Math.round($this.sizes.w),
  					height: Math.round($this.sizes.h)
  				});
  				
  				var top = from.top + (to.top-from.top)*now - $this.ptr.height()/2;
  				if($this.options.alwaysOnTop)
    				if(top < -$this.options.shadowSize) top = -$this.options.shadowSize;

  				$this.ptr.css({
  					left: from.left + (to.left-from.left)*now - $this.ptr.width()/2,
  					top: top
  				})

  				if(!$.browser.msie && !$this.is.opened)
  					$this.ptr.css({ opacity: to.opacity*now })
  					
  				if(!$.browser.msie && $this.is.closing)
					  $this.ptr.css({ opacity: (1-now) });

  				$this.setLimit();

  			}, speed, animation, function(){

  			  if(settings.message && $this.is.loading){
  			    $this.o.content.append("<span>" + settings.message + "</span>");
  			  }
  			  
  			  if(to && to.overflowY){
  			    $this.o.content.css({ overflowY: to.overflowY })
  			  }

          $this.is.animate = false;
          $this.is.opened = true;
          $this.check();
  			})

      }
      
      
    },
		setLimit: function(){
			var t = Math.round(this.o.pt + this.sizes.h/2);
			if(t > this.o.eh) t = this.o.eh;
			
			var l = Math.round(this.o.pl + this.sizes.w/2);
			if(l > this.o.ew) l = this.o.ew;
			
			this.o.oh.css({ height: t });
			this.o.ot.css({ top: t });
			if($.browser.msie && $.browser.version < 7 && this.o.ob.parent().height() % 2) t--;
			this.o.ob.css({ bottom: t });

			this.o.ow.css({ width: l });
			this.o.ol.css({ left: l });
			if($.browser.msie && $.browser.version < 7 && this.o.or.parent().width() % 2) l--;
			this.o.or.css({ right: l });
			
		},
    normalize: function(obj){
      var defs = { // default coords and sizes
        width: 30,
        height: 30,
        left: $(window).width()/2,
        top: $(window).height()/2,
        opacity: 1
      }
      
      if(obj){
        var jobj = $(obj);
        if(obj.length > 0 || obj.tagName){ //domNode
          defs.width = jobj.width() > defs.width ? jobj.width() : defs.width;
          defs.height = jobj.height() > defs.height ? jobj.height() : defs.height;
          
          var _offset = jobj.offset();
          defs.left = _offset.left+defs.width/2;
          defs.top = _offset.top+defs.height/2-$(window).scrollTop();
          
        } else { // size object
          if(obj.width < 30) delete obj.width;
          if(obj.height < 30) delete obj.height;
          $.extend(defs, obj)
        }
      }
      
      if( defs.height > $(window).height()-20){
        defs.height = $(window).height()-20;
        defs.overflowY = "auto";
      }
      
      return defs;
    },

    
    show: function( data, settings ){
      var $this = this;
      var jData = $(data);
      
      if( $.browser.msie && $.browser.version < 7 )
        this.ptr.parents("." + this.options.classFixed).show();
        
      if( settings && settings.onclose && $.isFunction(settings.onclose) )
        this.events.onclose = settings.onclose;
      else
        this.events.onclose = null;

      switch( typeof data ){
        case "number":
          this.showByCacheId(data, settings);
          break;
          
        case "string":

          if(jData.length > 0){
            // console.log("TODO: animate -> string object")

          } else if(data.split(":")[0] == "remote"){
            var url = data.split(":")[1];
            this.showRemote(url, settings);

          } else if(data.split(":")[0] == "image"){
            var src = data.split(":")[1];
            this.showImage(src, settings);

          } else {
            this.animate(from, to ? to : { width: 200, height: 200 });
            // console.log("TODO: animate -> text")

          }

          break;

        case "object":
          if(jData.length > 0){
            this.showNode(jData, settings);
          }

          break;

      }

    },
    close: function(settings){
      if(!this.is.closing && this.is.opened){
        this.addQueue(function(){
          this.is.closing = true;

          if(this.is.loading)
            this.preload(false);

          if(!settings.to) settings.to = {};
          $.extend(settings.to, { width: 0, height: 0 })
          this.animate(settings);
        });
        this.addQueue(function(){
          if($.browser.msie && $.browser.version < 7)
            this.ptr.parents("." + this.options.classFixed).hide();

          this.underLayer.hide();
          //this.ptr.hide();
          this.ptr.css({ left: -9999, top: -9999 })
          this.o.content.children().hide();

          this.is.opened = false;
          this.is.closing = false;
          
          if(this.events && this.events.onclose && $.isFunction(this.events.onclose))
            this.events.onclose.call(this);
          
        });
      }
    },
    preload: function(settings){
      if(settings){
        this.addQueue(function(){
          this.is.loading = true;

          this.o.content.children().hide();
          this.ptr.addDependClass("loading");
          if(settings.success)
            this.ptr.addDependClass("loading-success");

          if(!settings.to) settings.to = {};
          $.extend(settings.to, this.options.preload);
          this.animate(settings);
        });
      } else {
        this.ptr.removeDependClass("loading");
        this.ptr.removeDependClass("loading-success");
        this.is.loading = false;
        this.o.content.children().hide();
      }
        
    },
    append: function(node, settings){
      var uid = (new Date()).getTime() + Math.round(Math.random()*9999);
      node = $(node);

      // if(node.parent().length)
      //   node = node.clone(true);

		  node.appendTo(this.o.content);
      this.dimension();

      if(settings && settings.oncreate && $.isFunction(settings.oncreate))
        settings.oncreate.call(this, node);

		  var w = node.outerWidth();
		  var h = node.outerHeight();
		  
		  node.hide();
      this.dimension(false);

		  this.cache.push({ uid: uid, node: node, w: w, h: h });
		  
		  return uid;
      
    },
    dimension: function(hide){
      if($.browser.msie && $.browser.version < 7)
        if(hide === false){
    		  this.ptr.parent().hide();
        } else {
          this.ptr.parent().show()
        }
    },


    
    // data types
    showImage: function(src, settings){
      var cache = this.inCache(src);
      if(cache){
        this.preload(false);

        this.o.content.html("<img src='" + cache.src + "' />");
        if(!settings.to) settings.to = new Object();
			  $.extend(settings.to, { width: cache.w, height: cache.h });
        this.animate(settings);

      } else {
        var $this = this;
        this.preload(settings);

        var image = $("<img src='" + src + "' />");
        if($.browser.msie && $.browser.version < 7)
          $("." + this.options.classFixed).append(image);
        else
          $(document.body).append(image);
				image.css({ position: "absolute", left: -9999, top: -9999, border: "none" });

				image.load(function() {
				  var w = image.width();
				  var h = image.height();
				  $this.cache.push({ src: src, w: w, h: h })

          $this.addQueue(function(){
            this.preload(false);
            this.o.content.html("<img src='" + src + "' />");
    			  $.extend(settings.to, { width: w, height: h })
    			  settings.from = null;
            this.animate(settings);
          })
					image.remove();
				});
      }
    },

    // data types
    showRemote: function(url, settings){
      var cache = this.inCache(url);

      if(cache && !settings.reload){
        this.preload(false);

        cache.node.show();
        if(!settings.to) settings.to = new Object();
			  $.extend(settings.to, { width: cache.w, height: cache.h });

        this.animate(settings);

      } else {
        var $this = this;
        
        if(cache && settings.reload)
          this.cleanCache(cache);
        
        var request = {
          url: url,
          dataType: "html",
          success: function(data){
            var node = $(data).css({ visibility: "hidden", position: "absolute", left: -9999, top: -9999 });
            
            var queue = $this.queueCount;

    			  node.appendTo($this.o.content);
  				  var w = node.outerWidth();
  				  var h = node.outerHeight();
  				  node.hide();

    			  if(w*h == 0){
    			    if($this.queueCount == queue){
      			    $this.close(settings);
    			    }
    			  } else {
              if(!settings.reload)
      			    $this.cache.push({ url: url, node: node, w: w, h: h });

              $this.addQueue(function(){
                this.preload(false);

                node.removeAttr("style");

        			  $.extend(settings.to, { width: w, height: h })
        			  settings.from = null;
                this.animate(settings);
              })
    			  }

            
          }
        }
        
        if(settings.serialize){
          var form = $("#" + settings.serialize);
          var data = { data: form.serialize(), type: form.attr("method") ? form.attr("method").toUpperCase() : "POST" };
          $.extend(request, data);
        }
        
        this.preload(settings);
        $.ajax(request)

      }
    },

    showNode: function(node, settings){
      var cache = this.inCache(node.get(0));
      if(cache){
        this.showByCacheId(cache.uid, settings);
      } else {
        var uid = this.append(node);
		    this.cache.push({ node: node.get(0), uid: uid });
        this.showByCacheId(uid, settings);
      }
    },

    
    showByCacheId: function(uid, settings){
      var cache = this.inCache(uid);
      if(cache){
        this.preload(false);
        
			  cache.node.show();

			  if(settings && settings.onshow && $.isFunction(settings.onshow))
			    settings.onshow.call(this, cache.node);

        if(!settings.to) settings.to = new Object();
			  $.extend(settings.to, { width: cache.w, height: cache.h });
        this.animate(settings);
      }
    }

  }
  
})(jQuery);

/* Subscription object */

(function($) {
	$(document).ready(function(){
		if($('div.l-subscriptions').length != 0){
			var subscription = new Subscription();
			subscription.init();
		}
	});

	function Subscription(){
	
	}

	Subscription.prototype = {
		init:function(){
			var _my = this;
			this.flows = $('div.l-subscriptions ul.list li');
			this.flowNameBlock = $('div.l-subscriptions ul.list li div.short');
			this.flowName = $('div.l-subscriptions ul.list li div.short p b');
			this.flowSubscrIcon = $('div.l-subscriptions ul.list li div.short p span');
			this.flowNameBlock.hover(function(){
				$(this).parent().addClass('hover');
			}, function(){
				$(this).parent().removeClass('hover');
			});
			this.flowName.click(function(){
				_my.closeFlow(_my.flows)
				if($(this).parents('li').is('.open')){
					_my.closeFlow($(this).parents('li'));
				} else {
					_my.openFlow($(this).parents('li'));
				}
			});
			this.flowSubscrIcon.click(function(){
				if(!$(this).parents('li').is('.open')){
					_my.closeFlow($(this).parents('li'));
				}
			});
		},
		closeFlow:function(elem){
				var open = $('li.open');
				toClose = open.find('div.full')
				$( '.links .update', toClose).hide()
				toClose.animate({height:0}, 'fast', function(){
					open.removeClass('open');
				});
		},
		openFlow:function(elem){
			if(!elem.is('.open')){
				elem.addClass('open');
				elem.find('div.full').animate({height:105}, 'fast');
			}
		}
	}
})(jQuery);

/* Subscription object (end) */


/*
  Gallery preview class.
  Written by Egor Hmelyoff (hmelyoff@gmail.com)

  b_gallery_object.show( position );

*/

(function( $ ) {
  
  OPTIONS = {
    previewClass : "b-gallery-preview",
    dataClass    : "b-gallery-preview-data",
    
    buttonLeft   : "b-gallery-left",
    buttonRight  : "b-gallery-right",
    
    updateClass  : "j-gallery-preload",
    
    limit        : 10,
    preload      : 10,
    cache        : 1,
    width        : 77,
    
    fetch        : Array()
  };

  var w = this;
  $( document ).ready(function(){
    $(".b-gallery").each(function(){
      w.b_gallery_object = new b_gallery( this );
    })
  });
  
  function b_gallery(){
  	return this.init.apply( this, arguments );
  };
  
  b_gallery.prototype = {
    init: function( obj, options ){
      this.options = $.extend( {}, OPTIONS, options ? options : {} );
      this.domNode = $( obj );
      this.previewNode = this.domNode.find("." + this.options.previewClass);
      this.previewNode.css({ width: this.previewNode.outerWidth(), height: this.previewNode.outerHeight() });

      this.buttons = {
        left: this.domNode.find("." + this.options.buttonLeft),
        right: this.domNode.find("." + this.options.buttonRight)
      };
      
      // get global settings
      var initOptions = this.domNode.attr("json");
      if( initOptions ){
        initOptions = eval("(" + initOptions + ")");
        $.extend( this.options, initOptions );
      }
      
      // fetch data from html
      this._data = new Array();
      var _data = this.fetch( this.options.dataClass );
      if(_data) this._data = _data;
      
      this.prepare();
      this.bindEvents();
      this._show(0);
    },
    
    fetch: function( options ){
      var self = this;
      var _data = new Array();

      switch( typeof options ){

        case "string":
          this.domNode.find("." + options).find("a img").each(function(){
            var o = $( this );
            var json = o.attr("json")
            if( json ){
              json = eval("(" + json + ")");
              _data[json.position] = json;
            }
          }).end().remove();
          
          return _data;

          break;

        case "object":
          if(!this.options.fetch["d"+options.direction]){
            this.options.fetch["d"+options.direction] = true;
            $.ajax({
              type: "GET",
              url: this.options.previews_url,
              data: "photo_id=" + options.last.id + "&direction=" + ((options.direction < 0) ? "backward" : "forward"),
              dataType: "json",
              success: function(json){
                self.options.fetch["d"+options.direction] = false;
                for (var i=0; i < json.length; i++) {
                  self._data[json[i].position] = json[i];
                };
                self._show(0);
              },
              error: function(){
                self.options.fetch["d"+options.direction] = false;
                self.fetch( options );
              }
            })
          }
        
        
          break;
      }
      
      return false;
    },
    
    prepare: function(){
      this.options.center = this.options.position;
      this._preload();
    },
    
    bindEvents: function(){
      var self = this;
      this.buttons.left.click(function(){
        self._show(-1);
      })
      this.buttons.right.click(function(){
        self._show(1);
      })
    },
    
    show: function( prev, next, event ){
      event = $.event.fix(event);
      var updateLayer = $("." + this.options.updateClass);
      
      if( event.pageX-updateLayer.offset().left > updateLayer.width()/2 ){
        position = next;
      } else {
        position = prev;
      }
      
      if( position ){
        this.options.center = this.options.position = position;
        this._preload();
        this._render( position );
      }
    },
    
    _show: function( dir ){
      var self = this;
      
      this.options.center += dir;
      if(this.options.center < 1) this.options.center = 1;
      if(this.options.center > this.options.photos_count) this.options.center = this.options.photos_count;

      var img = this._get( this.options.center, 3 );
      this.previewNode.empty()
 
      for ( var i=0; i < img.length; i++ ) {
        if( img[i] ){
          var html;
          (function(cur){
            html = $('<div' + (img[cur].position == self.options.position ? ' class="current"><i style="width: ' + (img[cur].dimensions.width+2) + 'px; height: ' + (img[cur].dimensions.height+2) + 'px;"></i>' : '>' ) + '<img src="' + img[cur].image + '" width="' + img[cur].dimensions.width + '" height="' + img[cur].dimensions.height + '" /></div>')
              .find("img").click(function(){
                if(!self.options.loading){
                  self._render( img[cur].position )
                }
              }).end();
          })(i);


        } else if (img[1].position != 1 && img[1].position != this.options.photos_count){
          var html = $('<div class="loading"><img src="/images/d.gif" width="' + img[1].dimensions.width + '" height="' + img[1].dimensions.height + '" /></div>');
        }
        
        if(html){
          this.previewNode.append(html.css({ left: i*this.options.width+10, position: "absolute", top: 8 }));
          html = null;
        }
        
      };

      this._cache();
      this._preload();
    },
    
    _render: function( position ){
      var self = this;
      if(typeof this._data[position].cache == 'string'){
        eval(this._data[position].cache);
        this._data[position].cache = null;

      } else if(this._data[position].cache === true){
        layer();

      } else {
        layer();

        $.ajax({
          type: "GET",
          url: this._data[position].ajax_url,
          dataType: "script",
          success: function(){
            self.options.loading = false;
            $(".b-gallery-layer").remove();
          },
          error: function(){
            $(".b-gallery-layer").remove();
          }
        })
        
      }
      
      window.location.hash = "#redirect-" + this._data[position].id;
      this.options.center = position;
      this.options.position = position;
      this._show(0);

      function layer(){
        self.options.loading = true;

        var updateLayer = $("." + self.options.updateClass);
        $('<div class="b-gallery-layer"></div>')
          .css({ width: updateLayer.width(), height: updateLayer.height(), left: updateLayer.offset().left, top: updateLayer.offset().top, opacity: 0 })
          .appendTo(document.body)
          .animate({ opacity: 0.8 });
      }

    },
    
    _get: function( current, count ){
      var self = this;
      var _data = new Array();
      var _left = Math.floor((count-1)/2);
      var _right = (count-1)-_left;
      
      for ( var i=0; i < this._data.length; i++ ) {
        if( this._data[i] && current == this._data[i].position )
          break;
      };
      
      for ( var k=i-_left; k < i; k++ ) {
        _data.push(this._data[k]);
        if(this._data[k]) button("left", false);
        else button("left", true);
      };

      for ( var k=i; k <= i+_right; k++ ) {
        _data.push(this._data[k]);
        if(this._data[k]) button("right", false);
        else button("right", true);
      };
      
      function button(type, state){
        self.buttons[type].find("button").get(0).buttonHandler.state("disabled", state);
      }
      
      return _data;
    },
    
    _preload: function(){
      var self = this;
      
      var _left = this.options.center-this.options.preload;
      if( _left < 1 ) left = 1;

      var _right = this.options.center+this.options.preload;
      
      for ( var i=_left; i <= _right; i++ ) {
        if( this._data[i] && !this._data[i].preloaded ){
          this._data[i].preloaded = true;
          var img = $('<img src="' + this._data[i].image + '" />').css({ left: -10000, top: -10000, position: "absolute" });
          img.appendTo( document.body );
          img.load(function(){
            //$( this ).remove();
          })
        }
        
        if( !this._data[i] && i > 1 && i < this.options.photos_count ){
          if(this._data[i+1])
            this.fetch({ last: this._data[i+1], direction: -1 })
          if(this._data[i-1])
            this.fetch({ last: this._data[i-1], direction: 1 })
        }
      };
      
    },
    
    _cache: function(){
      var self = this;

      for (var i=this.options.position+1; i <= this.options.position+this.options.cache; i++) {
        load(i);
      };

      for (var i=this.options.position-this.options.cache; i < this.options.position; i++) {
        load(i);
      };
      
      function load(i){
        if(self._data[i] && !self._data[i].cache){
          self._data[i].cache = true;
          // console.log(self.options.center + ", now: " + i);
          $.ajax({
            type: "GET",
            url: self._data[i].ajax_url,
            dataType: "text",
            success: function(data){
              self._data[i].cache = data;
              if(self._data[i].position == self.options.center){
                eval(data);
                self.options.loading = false;
                $(".b-gallery-layer").remove();
              }
            },
            error: function(){
              $(".b-gallery-layer").remove();
            }
          })

          if(!self._data[i].image_original_preload){
            var img = $('<img src="' + self._data[i].image_original + '" />').css({ left: -10000, top: -10000, position: "absolute" });
            img.appendTo( document.body );
            self._data[i].image_original_preload = true;
          }

        }
      }
      
    }

  };

})(jQuery);


(function($){
  
  $( document ).ready(function(){
    $(".j-accordion").each(function(){
      new accordion( this );
    })
  })
  
  function accordion(){ return this.init.apply(this, arguments); }
  accordion.prototype = {

    init: function( obj ){
      var self = this;
      this.ptr = $(obj);
      this.a = new Array();

      this.ptr.find(".j-accordion-container").each(function(){
        self.a.push({ ptr: $(this), selected: $(this).attr("selected") == "true" ? true : false })
      })
      
      $.each(this.a, function(){
        var a = this;
        this.ptr.mouseover(function(){
          if(!a.selected)
            self.show(a);
        })
        
      })

    },
    
    show: function( obj ){
      this.hide();

      obj.selected = true;
      var data = obj.ptr.addDependClass("visible").find(".j-accordion-data");
      
      if(!($.browser.msie && $.browser.version < 8)){
        var _h = data.outerHeight();

        data.css({ overflow: "hidden", height: 0, opacity: 0 }).animate({ height: _h, opacity: 1 }, 200, function(){
          $(this)
            .removeAttr("style")
        });
      }
    },
    
    hide: function(){
      $.each(this.a, function(){
        if( this.selected ){
          
          this.selected = false;
          
          if($.browser.msie && $.browser.version < 8){
            this.ptr.removeDependClass("visible");
          } else {
            this.ptr.find(".j-accordion-data").css({ overflow: "hidden" }).stop().animate({ height: 0, opacity: 0 }, 200, function(){
              $(this)
                .removeAttr("style")
                .parents(".j-accordion-container")
                  .removeDependClass("visible");
            });
          }
          
        }
      })
    }

  }
  
  
})( jQuery );

(function( $ ){
  
  var OPTIONS = {
    BASECLASS: "{baseClass}",
    
    panelSelector: ".b-user-panel-container",
    className: "b-user-panel-dropdown",
    parentSelector: ".b-user-panel-button",
    textSelector: ".b-user-panel-dropdown-container",
    
    sizes: {
      preloadHeight: 24
    },

    speed: 400, //ms
    speedSlow: 4000, //ms
    
    animation: "swing",
    animationClose: "easeInBack",
    
    template:
      '<div class="{baseClass}">' +
        '<div class="{baseClass}-shadow">' +
          '<div class="l"><div><i></i></div></div>' +
          '<div class="r"><div><i></i></div></div>' +
          '<div class="b"><div class="b-l"><i></i></div><div class="b-r"><i></i></div></div>' +
        '</div>' +
        '<div class="{baseClass}-container">' +
        '</div>' +
      '</div>'
  }
  
  var Helper = {
    replaceAll: function(str, old, rep) {
        var rExp = new RegExp(old, "g");
        return(str.replace(rExp, rep));
    }
  };
  
  this.bUserPanel = {
    
    buttons: [],

    show: function( data, settings ){
      var self = this;
      var jData = $(data);
      
      var event = $.event.fix(settings.event);
      if(!$(event.target).is("i") && !settings.force) return true;
      
      switch( typeof data ){
        case "number":
          //this.showByCacheId(data, settings);
          break;
          
        case "string":
          if( jData.length > 0 ){
            this.showNode(jData, settings);

          } else if( data.split(":")[0] == "remote" ){
            var url = data.split(":")[1];
            this.showRemote(url, settings);

          } else {
            // console.log("TODO: animate -> text")

          }

          break;

        case "object":
          if( jData.length > 0 ){
            // this.showNode(jData, settings);
          }

          break;

      }
      
      return false;
    },
    
    hide: function( except ){
      for( var i=0; i < this.buttons.length; i++ ){
        if( this.buttons[i].isOpened() && this.buttons[i] != except )
          this.buttons[i].hide();
      };
    },
    
    showRemote: function( url, settings ){
      if( settings.node ){
        var button = this.byNode( settings.node );
        this.hide( button );
        button.showRemote( url, settings );

      } else return false;
    },

    showNode: function( node, settings ){
      if( settings.node ){
        var button = this.byNode( settings.node );
        this.hide( button );
        button.showNode( node, settings );

      } else return false;
    },
    
    byNode: function( node ){
      var root = $(node).parents("." + OPTIONS.className);

      for (var i=0; i < this.buttons.length; i++) {
        if(this.buttons[i].buttonNode.get(0) == node || this.buttons[i].domNode.get(0) == root.get(0))
          return this.buttons[i];
      };
      
      this.buttons.push( new bUserPanel.Button( node ) );
      return this.buttons[this.buttons.length-1];
      
    },
    
    flushCache: function( node ){
      for (var i=0; i < this.buttons.length; i++) {
        if( node ){
          if( this.buttons[i].buttonNode.get(0) == node )
            this.buttons[i].flushCache();
        } else
          this.buttons[i].flushCache();
      };
    }
    
  }
  
  bUserPanel.Button = function(){ return this.init.apply(this, arguments); }
  bUserPanel.Button.prototype = {
    init: function( node ){
      // Create dropdown node
      this.buttonNode = $(node);
      this.rootNode = $(this.buttonNode).parents(OPTIONS.parentSelector);
      
      this.domNode = this.rootNode.find("." + OPTIONS.className);
      if(!this.domNode.length){
        this.domNode = OPTIONS.template;
        this.domNode = Helper.replaceAll(this.domNode, OPTIONS.BASECLASS, OPTIONS.className);
        this.domNode = $(this.domNode);
        $(this.buttonNode).parent().append(this.domNode);
      }
      this.textNode = this.domNode.find(OPTIONS.textSelector)
      this.domNode.hide();
      
      // defaults
      this.is = {
        animate: false,
        loading: false,
        closing: false,
        opened : false
      }
      this.cache = [];
      this.current = null;
      
      var self = this;
      var clicked = false;
      $(document.body).click(function(){
        if( !clicked && self.isOpened() )
          self.hide()
        else
          clicked = false;
      })
      this.rootNode.click(function(){
        clicked = true;
      })
      
    },
    
    inCache: function( data ){
      for( var i=0; i < this.cache.length; i++ ){
        if( this.cache[i].uid && this.cache[i].uid == data )
          return this.cache[i];

        if( this.cache[i].src && this.cache[i].src == data )
          return this.cache[i];

        if( this.cache[i].url && this.cache[i].url == data )
          return this.cache[i];

        if( this.cache[i].node && this.cache[i].node == data )
          return this.cache[i];
      };
      return false;
    },
    
    cleanCache: function( cache ){
      for( var i=0; i < this.cache.length; i++ ){
        if( this.cache[i] == cache )
          break;
      }
      this.cache.splice(i, 1);
    },
    
    isOpened: function(){
      return ((!this.is.closing && this.is.opened) || this.is.loading);
    },
    
    blink: function( node, b ){
      if(this.is.loading){
        var self = this;
        b = !b;
        if(b) var o = 1; else var o = 0;
        node.animate({ opacity: o }, 200, function(){
          self.blink( node, b );
        })
      } else {
        node.removeAttr("style");
        return false; 
      }
      
    },
    
    preload: function( settings ){
      if( settings || settings !== false ){
        this.is.loading = true;
        this.blink( this.buttonNode.find("i"), true );
      } else {
        this.is.loading = false;
      }
    },
    
    animate: function( node ){
      var self = this;

      if( !this.is.animate ){
        this.is.animate = true;

        var panel = $(OPTIONS.panelSelector);
        var maxh = $(window).height() - panel.height();
        var scroll = false;

        if( this.sizes.w < this.buttonNode.outerWidth() ) this.sizes.w = this.buttonNode.outerWidth();
        if( this.sizes.h > maxh){
          this.sizes.h = maxh;
          scroll = true;
          this.sizes.w += 20;
        }
        
        this.domNode.show();
        if(node)
          node.removeAttr("style").css({ width: this.sizes.w, height: this.sizes.h });
        else
          this.textNode.children().css({ overflowY: "hidden" });
        
        var animation = OPTIONS.animation;
        if(this.is.closing)
          animation = OPTIONS.animationClose;
          

        if((this.domNode.offset().left - panel.offset().left + this.sizes.w > panel.outerWidth()) || (this.is.closing && this.is.right)){
          this.is.right = true;
          this.domNode.css({ left: "auto", right: this.rootNode.width() - (this.buttonNode.outerWidth() + this.buttonNode.offset().left-this.rootNode.offset().left) - 10 });
        } else {
          this.domNode.css({ left: this.buttonNode.offset().left-this.rootNode.offset().left-10 });
        }
        if(this.textNode.outerWidth() < this.buttonNode.outerWidth()) this.textNode.css({ width: this.buttonNode.outerWidth() });
        this.textNode.animate({ width: this.sizes.w, height: this.sizes.h }, OPTIONS.speed, animation, function(){
          if(scroll){
            node.css({ position: "relative", overflowY: "auto" });
          }
          
          self.is.animate = false;
          self.is.opened = true;
          if(self.is.closing){
            self.is.closing = false;
            self.is.opened = false;
            self.domNode.hide();
          }
        })
        
        
      }
      
    },
    
    showRemote: function( url, settings ){
      var self = this;
      var cache = this.inCache(url);
      
      if( this.isOpened() && url == this.current ){
        this.hide( settings );

      } else {
        this.rootNode.addDependClass("selected").css({ zIndex: 10 });
        this.is.opened = true;
        
        if( cache && !settings.reload ){
          this.sizes = {
            w: cache.w,
            h: cache.h
          }
          self.textNode.children().hide();
          this.current = url;
          this.animate( cache.node );
        } else {
          var request = {
            url: url,
            dataType: "html",
            success: function( data ){
              var node = $(data).css({ visibility: "hidden", position: "absolute", left: -9999, top: -9999 });
              
              self.domNode.show();
      			  node.appendTo(self.textNode);
      			  self.sizes = {
      			    w: node.outerWidth(),
      				  h: node.outerHeight()
      			  }
    				  node.hide();
              self.domNode.hide();
              
              if( !settings.reload )
      			    self.cache.push({ url: url, node: node, w: self.sizes.w, h: self.sizes.h });
              
              if( self.isOpened() ){
                self.preload( false );
                self.textNode.children().hide();
                self.current = url;
                self.animate( node );
              }
              
            }
          }

          if( settings.serialize ){
            var form = $("#" + settings.serialize);
            var data = { data: form.serialize(), type: form.attr("method") ? form.attr("method").toUpperCase() : "POST" };
            $.extend(request, data);
          }

          this.preload( settings );
          $.ajax(request)
          
        }

      }
    },
    
    showNode: function( node, settings ){
      if( this.isOpened() ){
        this.hide( settings );

      } else {
        this.rootNode.addDependClass("selected").css({ zIndex: 10 });
        this.is.opened = true;
      
        this.domNode.show();
  		  node.css({ visibility: "hidden", position: "absolute", left: -9999, top: -9999 }).appendTo(this.textNode);
  		  this.sizes = {
  		    w: node.outerWidth(),
  			  h: node.outerHeight()
  		  }
  		  node.hide()
  		  this.domNode.hide();
  		  
        this.preload( false );
        this.animate( node );
        
      }
    },
    
    hide: function(){
      if(!this.is.loading){
        this.is.closing = true;
        this.sizes = { w: 0, h: 0 }
        this.animate();
      }
      this.is.loading = false;
      this.is.opened = false;
      this.rootNode.removeDependClass("selected").css({ zIndex: 9 });
    },
    
    flushCache: function(){
      for (var i=0; i < this.cache.length; i++) {
        if(this.cache[i].node)
          this.cache[i].node.remove();
      };
      this.cache = [];
      if( this.isOpened() ) this.hide();
      
    }

  }

})( jQuery );
(function( $ ){

  this.UserPanel = {
    change_style: function(variant){
      var variant_obj = $(variant).siblings().removeDependClass("selected").end().addDependClass("selected");

      jQuery.post("/user_panel/settings", {'profile[userpanel_version]': $.baseClass(variant_obj)});

      var style_classes = jQuery("body").attr('class').match(/(b-user-panel_([^ ]+))/i);
      if(style_classes && style_classes[1]){
        $(document.body).removeClass(style_classes[1]);
      }
      $(document.body).addClass("b-user-panel_" + $.baseClass(variant_obj));
    },
    toggle_pin: function(checkbox){
      jQuery.post("/user_panel/settings", {'profile[is_userpanel_pinned]': checkbox.checked});
      if(checkbox.checked){
        $(document.body).addClass("b-user-panel-fixed");
      }else{
        $.scrollTo(0, { duration: 400, easing: "easeOutExpo" });
        $(document.body).removeClass("b-user-panel-fixed");        
      }
    }
  }

})( jQuery );
/* Micro in header */
/*
(function($) {
  
	function debug(str) {
		if (window.console && window.console.log && GLOBAL.debug)
		window.console.log("[input.micro: '" + str + "']\n" + debug.caller.toString());
	};

  b_input_micro_OPTION = {
    selectorRoot: ".j-input-micro",
    selectorUpdateHTML: ".j-input-micro-update",
    selectorStatus: ".j-input-micro-status",

    selectorPlaceholder: ".placeholder",
    selectorPlaceholderType: {
      success: ".success"
    },

    selectorInput: "input",
    selectorSubmit: ".submit",

    colorFrom: "#ffffff",
    colorTo: "#ffef95"
  };
  
  $(document).ready(function(){
    b_input_micro.init({ debug: true });
  })
  
  this.b_input_micro = {
    init: function(options){
      this.options = $.extend(b_input_micro_OPTION, options ? options : {});
      this.ptr = $(this.options.selectorRoot);
      
      this.is = {
        init: false,
        input: false,
        submited: false
      }
      
      if(this.ptr.length){
        this.is.init = true;
        this.bindEvents();
      }
      
    },
    
    bindEvents: function(){
      var $this = this;
      this.ptr
        .mousedown(function(){
          focus();
    			if(!$this.is.input) return false;
    			else $this.is.input = false;
        })
        .mouseup(function(){
          $this.ptr.find($this.options.selectorInput).focus();
        })
        
      this.ptr.find(this.options.selectorInput)
        .focus(function(){
          focus();
        })
        .blur(function(){
          $this.ptr.removeDependClass("focused");
          if(this.value == "")
            $this.placeholder(true);
        })
        .mousedown(function(){
          $this.is.input = true;
        })
        
        var focus = function(){
          $this.ptr.addDependClass("focused");
          $this.placeholder(false);
        }
        
    },
    
    placeholder: function(b){
      var type;
      if(this.is.submited) type = "success";

      var p = this.ptr.find(this.options.selectorPlaceholder)
      if(b){
        p.show();
        if(type && this.options.selectorPlaceholderType[type]){
          p.hide().filter(this.options.selectorPlaceholderType[type]).show();
        } else {
          $.each(this.options.selectorPlaceholderType, function(){
            p.filter(this.toString()).hide();
          })
        }
      } else
        p.hide();
    },
    
    update: function(html){
      if(!this.is.init) return false;

      try{
        $(this.options.selectorUpdateHTML).replaceWith(html);
      }catch(e){
        debug(e);
      }
    },
    
    before: function(){
      if(!this.is.init) return false;
      var val = this.ptr.find(this.options.selectorInput).attr("value");
      if(val == "") { return false; }
      if(val.length > 388) { alert("Cлишком длинный текст микро"); return false; }
      this.ptr.addDependClass("loading");
      return true;
    },
    
    success: function(){
      if(!this.is.init) return false;
      var $this = this;

      this.is.submited = true;
      this.ptr.find(this.options.selectorInput).val("").blur();
      this.ptr.removeDependClass("loading");
      $(this.options.selectorStatus)
        .css({ backgroundColor: this.options.colorTo })
        .animate({ backgroundColor: this.options.colorFrom }, 1000)
    }
  }

})(jQuery);
*/
/* Micro in header (end) */

(function( $ ) {
  
  var list = new Array();

  $( document ).ready(function(){
    GLOBAL.reInit(function(){
      $(".j-dropdown").each(function(){
        list.push(new b_dropdown( this ));
      })
    })
  
  })
  
  function b_dropdown(){ return this.init.apply(this, arguments); }
  b_dropdown.prototype = {
    init: function( obj ){
      this.buttonNode = $(obj);
      this.buttonNode.removeClass("j-dropdown");

      this.is = {
        opened   : false,
        hovered  : false,
        centered : false
      }
      
      var results;
      var sClass = this.buttonNode.attr("class").split(" ");
      for (var i=0; i < sClass.length; i++) {
        var type = sClass[i].match(/j-dropdown_([^ ]+)/i);
        if(type && type[1]){
          this.is[type[1]] = true;
          this.buttonNode.removeClass("j-dropdown_" + type[1]);
        }
      };
/*
      while((results = /j-dropdown_([^ ]+)/g.exec(sClass)) != null){
        if(results[1]) this.is[results[1]] = true;
        this.buttonNode.removeClass("j-dropdown_" + results[1]);
      }
*/      
      var uid = this.buttonNode.attr("class").match(/j-dropdown-([^ ]+)/);
      if( uid[1] ){
        uid = uid[1];
        this.buttonNode.removeClass("j-dropdown-" + uid);
        this.containerNode = $("#"+uid);
        if(this.containerNode.length){
          this.containerNode.appendTo(document.body).wrap("<div class='b_dropdown_out'>");
          this.wrapNode = this.containerNode.parent();
          this.bindEvents();
        }
      }
      
      
    },
    
    bindEvents: function(){
      var self = this;
      var click = false;

      if(!this.is.hovered){
        this.buttonNode.click(function(){
          //click = true;
          if(self.is.opened){
            self.hide();
          } else {
            self.show();
          }
          return false;
        });
      }
      
      this.buttonNode.hover(function(){
        $(this).addDependClass("hover");
        if(self.is.hovered){
          if(self.hiding){ clearTimeout(self.hiding); self.hiding = null }
          else self.show();
        }
      }, function(){
        $(this).removeDependClass("hover");
        if(self.is.hovered){
          self.hiding = setTimeout(function(){ self.hide(); self.hiding = null }, 200);
        }
      })

      this.containerNode.click(function(){
        click = true;
      });

      if(this.is.hovered){
        this.containerNode.hover(function(){
          if(self.hiding){ clearTimeout(self.hiding); self.hiding = null }
        }, function(){
          self.hiding = setTimeout(function(){ self.hide(); self.hiding = null }, 200);
        })
      }
      
      $(document).click(function(){
        if(!click && self.is.opened)
          self.hide();
        else
          click = false;
      });
    },
    
    show: function(){
      
      for (var i=0; i < list.length; i++) {
        if(list[i].is.opened)
          list[i].hide();
      };
      
      var self = this;
      this.is.opened = true;

      var _height = this.containerNode.show().outerHeight();
      var _offset = this.buttonNode.offset();
      
      var _left = _offset.left;
      if(this.is.centered){
        _left = _left + this.buttonNode.outerWidth()/2 - this.containerNode.outerWidth()/2;
      }

      this.wrapNode.css({ position: "absolute", left: _left, top: _offset.top+this.buttonNode.outerHeight()+4, height: _height+1, zIndex: 50, overflow: "hidden" });
      this.containerNode.css({ position: "relative", top: -_height, opacity: 0 }).stop().animate({ top: 0, opacity: 1 }, 300, function(){
        self.containerNode.removeAttr("style").show().css({ position: "relative" });
      });
    },
    
    hide: function(){
      var self = this;
      this.is.opened = false;

      var _height = this.containerNode.show().outerHeight();
      this.containerNode.stop().css({ zIndex: 49 }).animate({ top: -_height, opacity: 0 }, 300, function(){
        self.containerNode.removeAttr("style");
        self.wrapNode.removeAttr("style");
      });
    }
  }
  

})( jQuery );

var Lameditor = {
	init: function() {
		if (jQuery('textarea').length > 0) {
			if (!Lameditor.loaded) {
				Lameditor.include_js("/javascripts/editor.js");
			} else {
				Launcher.init();
			}
		}
	},
	include_js: function(file) {
	    var html_doc = jQuery('head')[0];
	    var launched = false;
	    js = document.createElement('script');
	    js.setAttribute('type', 'text/javascript');
	    js.setAttribute('src', file);

		js.onreadystatechange = function () {
			if (js.readyState == 'loaded' || js.readyState == 'complete' && !launched) {
				Launcher.init();
				launched = true;
				Lameditor.loaded = true;
			}
	  };

	  js.onload = function () {
			if (!launched) {
				if (!Prototype.Browser.Opera) {Launcher.init();}
				launched = true;
				Lameditor.loaded = true;
			}
	  };
		html_doc.appendChild(js);
	    return false;
	}
};

/*global $, Launcher, document, jQuery, jsButton, jsSpan, lameditor */
// Сворачиваем форму в состояние ожидания, передаем сюда указатель DOM на форму
function commentAJAX(obj){
	var h = obj.find("div.cs-content").height();
	var _h = obj.removeClass("cs-form-full").addClass("cs-form-loading").find("div.cs-content").height();
	obj.addClass("cs-form-full").removeClass("cs-form-loading");
	
	obj.find("div.cs-content").css({ height: _h, overflow: "hidden" }).animate({ }, 500, function(){
		obj.removeClass("cs-form-full").addClass("cs-form-loading");
		jQuery(this).removeAttr("style");
	});
	obj.removeClass("cs-form-full").addClass("cs-form-loading");
	
	obj.find("div.cs-content-in").css({ opacity: 1 }).animate({ opacity: 0 }, 500, function(){
		jQuery(this).removeAttr("style");
	});

	// // //	Тест удаления формы			
	// setTimeout(function(){
	// 	removeForm(obj);
	// }, 600);
	
}


function commentFromInit(obj){
	obj
		.hover(function(){
			var $this = jQuery(this);
			if(!$this.is(".cs-form-full") && !$this.is(".cs-form-loading")){
				$this.addClass("cs-form-hover");
			}
		}, function(){
			var $this = jQuery(this);
			if(!$this.is(".cs-form-full") && !$this.is(".cs-form-loading")){
				$this.removeClass("cs-form-hover");
			}
		})
		.click(function(){
			var $this = jQuery(this);
			if(!$this.is(".cs-form-full") && !$this.is(".cs-form-loading")){
				$this.removeClass("cs-form-hover");
				var h = $this.find("div.cs-content").height();
				var _h = $this.addClass("cs-form-full").find("div.cs-content").height();
				$this.find("div.cs-content").css({ height: _h, overflow: "hidden" }); //.animate({ height: _h }, 500, function(){
					$this.find("div.cs-content").css({ height: "auto", overflow: "visible" });
				// });
				$this.find("div.cs-content-in").css({ opacity: 1 }); //.animate({ opacity: 1 }, 500, function(){
					//window.scrollTo(0, obj.offset().top);
				// });
			}
		})
		.find("span.cs-cancel")
			.unbind()
			.click(function(){
				var $this = jQuery(this).parents("div.cs-form").eq(0);
				$this.removeClass("cs-form-hover");
				var h = $this.find("div.cs-content").height();
				var _h = $this.removeClass("cs-form-full").find("div.cs-content").height();
				$this.addClass("cs-form-full");
				
				$this.find("div.cs-content-in").css({ opacity: 0 });
				//$this.find("div.cs-content-in").removeAttr("style");
				
				
				$this.find("div.cs-content").css({ height: _h, overflow: "hidden" }).removeClass("cs-form-full").animate({}, 500, function(){
					$this.removeClass("cs-form-full");
					jQuery(this).removeAttr("style");
				});

				if($this.parents("div.cs-group").length) {
					$this.css({ overflow: "hidden", height: 0, marginBottom: 0, paddingTop: 0 }).animate({}, 500, function(){
						$this.parent().prev().removeClass("cs-answered");
						$this.remove();
					});
					$this.parent().prev().removeClass("cs-answered");
					$this.remove();
				}
				
				$('form_comment_0').show();
				
			}).end()
		.find("div.cs-leave")
			.click(function(){
				var div = jQuery(this).parents("div.cs-comment").eq(0);
				commentAJAX(div);
				// reaction here
				div.find("form").get(0).onsubmit();
			});
	var jsspan = new jsSpan(obj.find("span.cs-cancel"));
}

function commentInitText(obj){
	obj.find(".cs-content img").each(function(){
		var $this = jQuery(this);
		var w = $this.width();
		if(w > obj.width()){
			$this.wrap("<div>").parent().addClass("cs-image-big").css({ width: obj.width()-10 }).append('<div><a target="_blank" href="' + $this.attr("src") + '">открыть картинку в новом окне</a></div>');
		}
	});
}


// Инит и функции для работы с комментами.

// Инитим комменты, передаем сюда указатель DOM на созданный коммент
function commentInit(obj){
	var jobj = jQuery(obj);
	
	commentInitText(jobj);
	
	jobj.
		hover(function(){
			if(jQuery.browser.msie){
				// jQuery(this).addClass("cs-comment-hover");
			} else {
				// jQuery(this).find("div.cs-answer").css({display:'block'}).stop().animate({ opacity: 1 }, "fast")
				// jQuery(this).find("div.cs-answer").css({opacity:1})
				// console.log(jQuery(this).find("div.cs-answer"))
			}
		}, function(){
			if(jQuery.browser.msie){
				// jQuery(this).removeClass("cs-comment-hover");
			} else {
				// jQuery(this).find("div.cs-answer").stop().animate({ opacity: 0 }, "fast")
			}
		}).find("div.cs-answer")
			.click(function(){
				var $this = jQuery(this).parents("div.cs-comment").eq(0);
				if(!$this.is(".cs-answered")){
					if(!$this.next("div.cs-group").length) {
						$this.after("<div class='cs-group' id=\"answers_"+$this.attr("id")+"\"></div>");
					}
			
					$this.addClass("cs-answered");
					var answer = jQuery("div.comments div.cs-form").eq(0).clone().attr('id', 'form_'+$this.attr("id"));
					answer.find("input[type=hidden]").eq(0).val($this.attr("id").replace('comment_', ''));
					$this.next().prepend(answer.removeClass("cs-form-full").removeClass("cs-form-loading").css({'display': 'block'}));
					commentFromInit(answer);
					answer.find(".cs-cancel").css({visibility: 'visible'});
					answer.find("textarea").empty();
					answer.find(".button-wrapper").each(function(){
						var jsbutton = new jsButton(jQuery(this));	
					});
					$('form_comment_0').hide();
					answer.click();
					
					if (lameditor.length > 0) {
						var source = jQuery("div.comments div.cs-form").find("textarea.lameditor")[0];
						var destination = answer.find("form")[0];
						answer.find("div.editor").remove();
						Launcher.clone(source, destination);
					}
				} else {
					$this.next().find("div.cs-form span.cs-cancel").eq(0).click();
				}
			});
}


// Удаляем форму после аякса, передаем сюда указатель DOM на форму
function removeForm(obj){
	var jobj = jQuery(obj);

	if(!jobj.parent().is(".cs-group-main")){
		jobj.css({ overflow: "hidden", height: 0, marginBottom: 0, paddingTop: 0, opacity: 0 }).animate({ }, 500, function(){
			jobj.parent().prev().removeClass("cs-answered");
			jobj.remove();
		});
		jobj.parent().prev().removeClass("cs-answered");
		jobj.remove();
	} else {
		var h = jobj.removeClass("cs-form-loading").find("div.cs-content").height();
		jobj.addClass("cs-form-loading");
		
		jobj.find("div.cs-content").css({ overflow: "hidden", height: h }).animate({ }, 500, function(){
			jobj.removeClass("cs-form-loading");
			jQuery(this).removeAttr("style");
		});
		jobj.removeClass("cs-form-loading");
		jobj.removeAttr("style");
	}
	
}

jQuery(document).ready(function(){
	
	
	Lameditor.init();
	// Инициализация формы для оставления комментария
	commentFromInit(jQuery("div.comments div.cs-form"));

	// too slow
	// if(!jQuery.browser.msie){
	// 	jQuery("div.comments div.cs-comment div.cs-answer").css({ opacity: 0 }).show()
	// }
	
	jQuery("div.comments div.cs-comment").each(function(){
		commentInit(this);
	});

	jQuery("div.cs-comment-text").hover(
	  function(){
	    jQuery("div.ru-comment").css({ visibility:"hidden" });
	    jQuery(this).prev().css({ visibility:"visible" });
	  },
	  function(){
	    //jQuery(this).prev().css({ visibility:"hidden" });
	  }
	);

	jQuery("div.cs-group-main").hover(
	  function(){ },
	  function(){
	    jQuery("div.ru-comment").css({ visibility:"hidden" });
	  }
	);
  if (window.location.hash.slice(0, 9) == "#comment_"){
    jQuery(window.location.hash).find(".cs-answer").trigger('click');
  }
});



(function( $ ){

  var OPTIONS = {
    classname: "b-slideshow",
    rootClass: ".b-slideshow",

    force: false,
    selfEvent: true,
    expanded: false,
    
    animation: "fade",
    speed: 300,
    title: "",
    fx: {},

    template: tmpl(
      '<div class="<%=classname%>-controls">' +
        '<h4 class="title"><%=title%></h4>' +
        '<div class="left"></div>' +
        '<div class="status"><%=status%></div>' +
        '<div class="right"></div>' +
        //'<div class="expand"><a class="g-pseudo-link" href="#"><span>показать все</span></a></div>' +
        '<div class="clear"><div></div></div>' +
      '</div>' +
      '<div class="<%=classname%>-photos">' +
      '</div>'
    ),
    
    statusTemplate: tmpl("<%=current%> / <%=count%>")
  };
  
  OPTIONS.fx.none = function(prev, next){
    prev.hide();
    next.show();
    console.log("none");
  };
  
  OPTIONS.fx.fade = function(prev, next){
    var self = this;
    next.show().css({ position: "absolute", left: "0", top: "0", opacity: "0" });
    this.photosNode.css({ height: Math.max(prev.outerHeight(), next.outerHeight()) })
    prev.animate({ opacity: 0 }, OPTIONS.speed);
    next.animate({ opacity: 1 }, OPTIONS.speed, function(){
      self.photosNode.css({ height: next.outerHeight() })
      prev.hide();
      next.removeAttr("style");
    });
  }
  
  $(document).ready(function(){
    $(OPTIONS.rootClass).each(function(){
      new bSlideShow( this );
    })
  });
  
  var bSlideShow = _Class.extend({
    init: function( node ){
      this.domNode = $(node);
      if(this.create()){
        this.bindEvents();
      }
    },
    
    create: function(){
      this.photos = this.domNode.children().hide().eq(0).show().end();
      
      this.OPTIONS = $.extend(true, {}, OPTIONS)
      try{
        var o = this.domNode.attr("settings");
        if(o && o.length){
          o = eval('(' + o + ')');
          $.extend(true, this.OPTIONS, o);
        }
      } catch(e){ };

      if(this.photos.length <= 1 && !this.OPTIONS.force) return false;
      
      this.status = {
        count: this.photos.length,
        current: 1
      }

      var template = $(this.OPTIONS.template(
        $.extend( true, {}, this.OPTIONS, { status: this.OPTIONS.statusTemplate(this.status) } )
      ));

      this.domNode.append(template);
      this.photos.appendTo(template.filter(this.OPTIONS.rootClass + "-photos"));
      this.photosNode = this.domNode.find(this.OPTIONS.rootClass + "-photos");
      this.controlsNode = this.domNode.find(this.OPTIONS.rootClass + "-controls");
      
      if(this.photos.length <= 1) this.controlsNode.children().not(".title, .clear").hide();
      
      this.title = '';
      try{
        this.title = this.domNode.parents(".b-article").find("h1");
        if(this.title.length)
          this.title = this.title.eq(0).text();
      } catch(e){ }
      
      return true;
    },
    
    bindEvents: function(){
      var self = this;
      this.controlsNode
        .find(".left")
          .mousedown(function(){
            return false;
          })
          .click(function(){
            self.show( -1 );
            track_event('Slideshow', 'Prev', self.title, self.status.current);
            return false;
          })
          .end()
        .find(".right")
          .mousedown(function(){
            return false;
          })
          .click(function(){
            self.show( 1 );
            track_event('Slideshow', 'Next', self.title, self.status.current);
            return false;
          })
          .end()
        .find(".expand a")
          .click(function(){
            self.photos.removeAttr("style").show();
            self.photosNode.removeAttr("style");
            return false;
          })
          
      if(this.OPTIONS.selfEvent)
        this.photos
          .mousedown(function(){
            return false;
          })
          .click(function(){
            self.show( 1 );
            track_event('Slideshow', 'Next', self.title, self.status.current);
            return false;
          })
          
    },
    
    show: function( dir ){
      if(!dir) dir = 1;
      
      var prev = this.photos.eq(this.status.current-1);

      this.status.current += dir;
      if(this.status.current < 1) this.status.current = this.status.count;
      if(this.status.current > this.status.count) this.status.current = 1;
      this.controlsNode.find(".status").html( this.OPTIONS.statusTemplate(this.status) )
      
      var next = this.photos.eq(this.status.current-1);

      this.OPTIONS.fx[ this.OPTIONS.animation && $.isFunction(this.OPTIONS.fx[this.OPTIONS.animation]) ? this.OPTIONS.animation : "none" ].call(this, prev, next);
      
    }
    
  });
  
})( jQuery );

(function( $ ){

  this.EventsViewtypeButton = {
    init: function(wrapper){
      this.events_wrapper = $(wrapper);
      var init_state = $.cookie("events_viewtype") || "mosaic";
      this.events_wrapper.addDependClass(init_state, "_");
    },
    onstatechange: function(old_state, new_state){
      $.cookie("events_viewtype", new_state);
      this.events_wrapper.removeDependClass(old_state, "_").addDependClass(new_state, "_");

      for (var i=0; i < oRating.ratingQueue.length; i++) {
        oRating.ratingQueue[i].reinit();
      };
    }
  };

  var Events = {
      hide_repeated_dates: function(){
      var prev_date = false;
      $(".b-event").each(function(){
        var event = $(this);
        var date = event.find(".j-event-date").html();
        if(date == prev_date){
          event.addDependClass("dateless", "_");
        }
        prev_date = date;
      });
    }
  };

  $(function() {
    EventsViewtypeButton.init(".b-events");

    // Скрываем повторяющиеся даты на странице топиков и на главной
    if(document.location.pathname.match(/\/$|\/topic/)){
      Events.hide_repeated_dates();
    }
  });
  
})( jQuery );


(function( $ ){
  
  this.MovieCalendar = _Class.extend({
    init: function( nodes, options ){
      this.dayNodes = nodes;
      this.options = options ? options : {};

      if( this.options.navigation ){
        this.navigation = this.dayNodes.filter("." + this.options.navigation);
        this.dayNodes = this.dayNodes.not("." + this.options.navigation);
      }
      
      this.bindEvents();
    },
    
    bindEvents: function(){
      var self = this;

      if( this.navigation ){
        this.navigation.eq(0).click(function(){
          self.show(-1);
          return false;
        }).css({ visibility: "hidden" });
        this.navigation.eq(1).click(function(){
          self.show(1);
          return false;
        })
      }
    },
    
    show: function( direction ){
      var current = this.dayNodes.filter(":visible");
      var last = current.eq(current.length-1);
      var next = last.next();

      if( next.is("." + this.options.navigation) )
        next = null;
        
      var first = current.eq(0);
      var prev = first.prev();
      if( prev.is("." + this.options.navigation) )
        prev = null;

      switch( direction > 0 ){
        case true:
          if( next ){
            next.show();
            first.hide();
          }
          break;
        case false:
          if( prev ){
            prev.show();
            last.hide();
          }
          break;
      }
      
      this.check();
    },
    
    check: function(){
      var current = this.dayNodes.filter(":visible");
      if( current.eq(0).prev().is("." + this.options.navigation) )
        this.navigation.eq(0).css({ visibility: "hidden" });
      else
        this.navigation.eq(0).css({ visibility: "visible" });

      if( current.eq(current.length-1).next().is("." + this.options.navigation) )
        this.navigation.eq(1).css({ visibility: "hidden" });
      else
        this.navigation.eq(1).css({ visibility: "visible" });

    }
    
  })
  
  
})( jQuery );

(function( $ ) {
  
  var OPTIONS = {

    rootSelector: ".b-reviews",
    newReviewSelector: ".b-review-new",
    formSelector: ".br-form",

    preloadClass: "br-preloading",
    flashClass: "br-flash",
    
    minimum: 250
  };
  
  $(document).ready(function(){

    // check onload
    Reviews.init();

    $(OPTIONS.rootSelector + " " + OPTIONS.newReviewSelector).find("textarea")
      .keyup(function(){ Reviews.check(); })
      .change(function(){ Reviews.check(); });

  });
  
  this.Reviews = {
    
    is: {
      init: false
    },
    
    init: function(){

      try{
        this.rootNode = $(OPTIONS.rootSelector);
        this.newReviewNode = this.rootNode.find(OPTIONS.newReviewSelector);
        this.textareaNode = this.newReviewNode.find("textarea");
        this.formNode = this.textareaNode.parents(OPTIONS.formSelector);
        this.counterNode = this.rootNode.find(".j-header-comments-count");

        this.check();
        this.is.init = true;
      } catch( e ){ };
      
    },
    
    // methods
    preload: function( status ){
      if( status ){
        this.formNode.find("button").get(0).buttonHandler.state("disabled", true);

        var preload = $('<div>').addClass(OPTIONS.preloadClass);
        var formOffset = this.formNode.offset();
        var fieldOffset = this.textareaNode.offset();

        this.textareaNode.after(preload);
        preload.css({ opacity: 0, left: fieldOffset.left-formOffset.left, top: fieldOffset.top-formOffset.top, width: this.textareaNode.outerWidth(), height: this.textareaNode.outerHeight() })
          .animate({ opacity: 0.8 });
        
      } else {
        this.formNode.find("button").get(0).buttonHandler.state("disabled", false);
        this.formNode.find("." + OPTIONS.preloadClass).remove();
      }
    },
    
    flash: function( message ){
      var button = this.formNode.find("button");
      button.get(0).buttonHandler.state("checked", false);
      
      var flash = $('<div>').addClass(OPTIONS.flashClass);
      flash.append("<span>" + message + "</span>");
      var formOffset = this.formNode.offset();
      var fieldOffset = this.textareaNode.offset();

      this.textareaNode.after(flash);
      flash.css({ opacity: 0.9, left: fieldOffset.left-formOffset.left, top: fieldOffset.top-formOffset.top, width: this.textareaNode.outerWidth(), height: this.textareaNode.outerHeight() });
      setTimeout(function(){
        flash.animate({ opacity: 0 }, function(){
          flash.remove();
        });
      }, 1000)
        
    },
    
    check: function(){
      var length = OPTIONS.minimum - this.textareaNode.val().length;
      var counter = this.formNode.find(".counter");
      var button = this.formNode.find("button");
      
      if(length <= 0){
        button.get(0).buttonHandler.state("disabled", false);
        counter.hide();
      } else {
        button.get(0).buttonHandler.state("disabled", true);
        counter.show().find("span").html( length );
      }
      
    },
    
    // events
    before: function(){
      if( !this.is.init )
        this.init();
      
      // review length check
      if( this.textareaNode.val().length < 250 ){
        this.flash("Слишком короткий отзыв");
        return false;
      }
      
      // TODO: review vote check
      if( !this.newReviewNode.find(".b-movie-vote .b-movie-vote-rating").width() ){
        this.flash("Поставте оценку фильму");
        return false;
      }
        
      
      this.preload( true );
      return true;
    },
    
    complete: function(){
      
    },
    
    failure: function(){
      button.get(0).buttonHandler.state("checked", false);
      this.preload( false );
      this.flash("Ошибка сервера");
    },

    update_counters: function(reviews_count){
      this.counterNode.show().html(reviews_count);
    }
  }

})( jQuery );

(function( $ ){
  
  var OPTIONS = {
    listSelector: ".j-tab-list",
    containerSelector: ".j-tab-container",
    controllerSelector: ".j-tab-controller"
  }
  
  $(document).ready(function(){
    $(".j-tabs").each(function(){
      new tabs(this);
    })
  })
  
  function tabs(){
    return this.init.apply(this, arguments);
  }
  
  tabs.prototype = {
    init: function(obj, options){
      
      this.options = $.extend(true, {}, OPTIONS, options ? options : {});
      
      this.domNode = $(obj);
      this.listNode = this.domNode.find(this.options.listSelector).show(); // show tab list
      this.controlNodes = this.listNode.find(this.options.controllerSelector);
      this.bindEvents();
      
    },
    
		bindEvents: function(){
			var self = this;
			selected_class = this.options.controllerSelector + '-selected';
			selected_class = selected_class.replace( /\./, '');

			this.controlNodes.each(function(i){
				var tab = $(this);
			
				tab.click(function(){
					self.controlNodes.removeDependClass("selected");

					$(this).addDependClass("selected");
					self.show(i);
					return false;
				})

				if ( tab.hasClass(selected_class)){
					self.show(i);
				}
			})

			if (this.listNode.find(this.options.controllerSelector + '-selected').length == 0 ){
				this.controlNodes.eq(0).addDependClass('selected');
				this.show(0);				
			}
		},
    
    show: function(i){
      this.domNode.find(this.options.containerSelector).hide().eq(i).show();
    }
  }

})( jQuery );
(function( $ ){
  
  var OPTIONS = {
    containerSelector: ".j-tab-container",
    controllerSelector: ".j-tab-controller"
  }
  
  $(document).ready(function(){
    $(".j-tabs-light").each(function(){
      new tabs_light(this);
    })
  })
  
  function tabs_light(){
    return this.init.apply(this, arguments);
  }
  
  tabs_light.prototype = {
    init: function(obj, options){
      
      this.options = $.extend(true, {}, OPTIONS, options ? options : {});
      
      this.domNode = $(obj);
      this.controlNodes = $(this.options.controllerSelector);

      this.bindEvents();
      
    },
    
    bindEvents: function(){
			var self = this;
			selected_class = this.options.controllerSelector + '-selected'
			selected_class = selected_class.replace( /\./, '')
			
			this.controlNodes.each(function(i){
				var tab = $(this);
			
				tab.click(function(){
					self.controlNodes.removeDependClass("selected");

					$(this).addDependClass("selected");
					self.show(i);
					return false;
				})
								
				if ( tab.hasClass(selected_class)){
					self.show(i);
				}
			})

			if ($(this.options.controllerSelector + '-selected').length == 0 ){
				this.controlNodes.eq(0).addDependClass('selected');
				this.show(0);
			}
    },
    
    show: function(i){
      $(this.options.containerSelector).hide().eq(i).show();
    }
  }

})( jQuery );
/*
 * WYMeditor : what you see is What You Mean web-based editor
 * Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
 * Dual licensed under the MIT (MIT-license.txt)
 * and GPL (GPL-license.txt) licenses.
 *
 * For further information visit:
 *        http://www.wymeditor.org/
 *
 * File: jquery.wymeditor.js
 *
 *        Main JS file with core classes and functions.
 *        See the documentation for more info.
 *
 * About: authors
 *
 *        Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
 *        Volker Mische (vmx a-t gmx dotde)
 *        Scott Lewis (lewiscot a-t gmail dotcom)
 *        Bermi Ferrer (wymeditor a-t bermi dotorg)
 *        Daniel Reszka (d.reszka a-t wymeditor dotorg)
 *        Jonatan Lundin (jonatan.lundin _at_ gmail.com)
 */

/*
   Namespace: WYMeditor
   Global WYMeditor namespace.
*/
if(!WYMeditor) var WYMeditor = {};

//Wrap the Firebug console in WYMeditor.console
(function() {
    if ( !window.console || !console.firebug ) {
        var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
        "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

        WYMeditor.console = {};
        for (var i = 0; i < names.length; ++i)
            WYMeditor.console[names[i]] = function() {}

    } else WYMeditor.console = window.console;
})();

jQuery.extend(WYMeditor, {

/*
    Constants: Global WYMeditor constants.

    VERSION             - Defines WYMeditor version.
    INSTANCES           - An array of loaded WYMeditor.editor instances.
    STRINGS             - An array of loaded WYMeditor language pairs/values.
    SKINS               - An array of loaded WYMeditor skins.
    NAME                - The "name" attribute.
    INDEX               - A string replaced by the instance index.
    WYM_INDEX           - A string used to get/set the instance index.
    BASE_PATH           - A string replaced by WYMeditor's base path.
    SKIN_PATH           - A string replaced by WYMeditor's skin path.
    WYM_PATH            - A string replaced by WYMeditor's main JS file path.
    SKINS_DEFAULT_PATH  - The skins default base path.
    SKINS_DEFAULT_CSS   - The skins default CSS file.
    LANG_DEFAULT_PATH   - The language files default path.
    IFRAME_BASE_PATH    - A string replaced by the designmode iframe's base path.
    IFRAME_DEFAULT      - The iframe's default base path.
    JQUERY_PATH         - A string replaced by the computed jQuery path.
    DIRECTION           - A string replaced by the text direction (rtl or ltr).
    LOGO                - A string replaced by WYMeditor logo.
    TOOLS               - A string replaced by the toolbar's HTML.
    TOOLS_ITEMS         - A string replaced by the toolbar items.
    TOOL_NAME           - A string replaced by a toolbar item's name.
    TOOL_TITLE          - A string replaced by a toolbar item's title.
    TOOL_CLASS          - A string replaced by a toolbar item's class.
    CLASSES             - A string replaced by the classes panel's HTML.
    CLASSES_ITEMS       - A string replaced by the classes items.
    CLASS_NAME          - A string replaced by a class item's name.
    CLASS_TITLE         - A string replaced by a class item's title.
    CONTAINERS          - A string replaced by the containers panel's HTML.
    CONTAINERS_ITEMS    - A string replaced by the containers items.
    CONTAINER_NAME      - A string replaced by a container item's name.
    CONTAINER_TITLE     - A string replaced by a container item's title.
    CONTAINER_CLASS     - A string replaced by a container item's class.
    HTML                - A string replaced by the HTML view panel's HTML.
    IFRAME              - A string replaced by the designmode iframe.
    STATUS              - A string replaced by the status panel's HTML.
    DIALOG_TITLE        - A string replaced by a dialog's title.
    DIALOG_BODY         - A string replaced by a dialog's HTML body.
    BODY                - The BODY element.
    STRING              - The "string" type.
    BODY,DIV,P,
    H1,H2,H3,H4,H5,H6,
    PRE,BLOCKQUOTE,
    A,BR,IMG,
    TABLE,TD,TH,
    UL,OL,LI            - HTML elements string representation.
    CLASS,HREF,SRC,
    TITLE,ALT           - HTML attributes string representation.
    DIALOG_LINK         - A link dialog type.
    DIALOG_IMAGE        - An image dialog type.
    DIALOG_TABLE        - A table dialog type.
    DIALOG_PASTE        - A 'Paste from Word' dialog type.
    BOLD                - Command: (un)set selection to <strong>.
    ITALIC              - Command: (un)set selection to <em>.
    CREATE_LINK         - Command: open the link dialog or (un)set link.
    INSERT_IMAGE        - Command: open the image dialog or insert an image.
    INSERT_TABLE        - Command: open the table dialog.
    PASTE               - Command: open the paste dialog.
    INDENT              - Command: nest a list item.
    OUTDENT             - Command: unnest a list item.
    TOGGLE_HTML         - Command: display/hide the HTML view.
    FORMAT_BLOCK        - Command: set a block element to another type.
    PREVIEW             - Command: open the preview dialog.
    UNLINK              - Command: unset a link.
    INSERT_UNORDEREDLIST- Command: insert an unordered list.
    INSERT_ORDEREDLIST  - Command: insert an ordered list.
    MAIN_CONTAINERS     - An array of the main HTML containers used in WYMeditor.
    BLOCKS              - An array of the HTML block elements.
    KEY                 - Standard key codes.
    NODE                - Node types.

*/

    VERSION             : "0.5-b2",
    INSTANCES           : [],
    STRINGS             : [],
    SKINS               : [],
    NAME                : "name",
    INDEX               : "{Wym_Index}",
    WYM_INDEX           : "wym_index",
    BASE_PATH           : "{Wym_Base_Path}",
    CSS_PATH            : "{Wym_Css_Path}",
    WYM_PATH            : "{Wym_Wym_Path}",
    SKINS_DEFAULT_PATH  : "skins/",
    SKINS_DEFAULT_CSS   : "skin.css",
    SKINS_DEFAULT_JS    : "skin.js",
	LANG_DEFAULT_PATH   : "lang/",
    IFRAME_BASE_PATH    : "{Wym_Iframe_Base_Path}",
    IFRAME_DEFAULT      : "iframe/default/",
    JQUERY_PATH         : "{Wym_Jquery_Path}",
    DIRECTION           : "{Wym_Direction}",
    LOGO                : "{Wym_Logo}",
    TOOLS               : "{Wym_Tools}",
    TOOLS_ITEMS         : "{Wym_Tools_Items}",
    TOOL_NAME           : "{Wym_Tool_Name}",
    TOOL_TITLE          : "{Wym_Tool_Title}",
    TOOL_CLASS          : "{Wym_Tool_Class}",
    CLASSES             : "{Wym_Classes}",
    CLASSES_ITEMS       : "{Wym_Classes_Items}",
    CLASS_NAME          : "{Wym_Class_Name}",
    CLASS_TITLE         : "{Wym_Class_Title}",
    CONTAINERS          : "{Wym_Containers}",
    CONTAINERS_ITEMS    : "{Wym_Containers_Items}",
    CONTAINER_NAME      : "{Wym_Container_Name}",
    CONTAINER_TITLE     : "{Wym_Containers_Title}",
    CONTAINER_CLASS     : "{Wym_Container_Class}",
    HTML                : "{Wym_Html}",
    IFRAME              : "{Wym_Iframe}",
    STATUS              : "{Wym_Status}",
    DIALOG_TITLE        : "{Wym_Dialog_Title}",
    DIALOG_BODY         : "{Wym_Dialog_Body}",
    STRING              : "string",
    BODY                : "body",
    DIV                 : "div",
    P                   : "p",
    H1                  : "h1",
    H2                  : "h2",
    H3                  : "h3",
    H4                  : "h4",
    H5                  : "h5",
    H6                  : "h6",
    PRE                 : "pre",
    BLOCKQUOTE          : "blockquote",
    A                   : "a",
    BR                  : "br",
    IMG                 : "img",
    TABLE               : "table",
    TD                  : "td",
    TH                  : "th",
    UL                  : "ul",
    OL                  : "ol",
    LI                  : "li",
    CLASS               : "class",
    HREF                : "href",
    SRC                 : "src",
    TITLE               : "title",
    ALT                 : "alt",
    DIALOG_LINK         : "Link",
    DIALOG_IMAGE        : "Image",
    DIALOG_TABLE        : "Table",
    DIALOG_PASTE        : "Paste_From_Word",
    BOLD                : "Bold",
    ITALIC              : "Italic",
    CREATE_LINK         : "CreateLink",
    INSERT_IMAGE        : "InsertImage",
    INSERT_TABLE        : "InsertTable",
    INSERT_HTML         : "InsertHTML",
    PASTE               : "Paste",
    INDENT              : "Indent",
    OUTDENT             : "Outdent",
    TOGGLE_HTML         : "ToggleHtml",
    FORMAT_BLOCK        : "FormatBlock",
    PREVIEW             : "Preview",
	
	UNLINK			     : "Unlink",
	INSERT_UNORDEREDLIST : "InsertUnorderedList",
	INSERT_ORDEREDLIST	 : "InsertOrderedList",

    MAIN_CONTAINERS : new Array("p","h1","h2","h3","h4","h5","h6","pre","blockquote"),

    BLOCKS : new Array("address", "blockquote", "div", "dl",
	   "fieldset", "form", "h1", "h2", "h3", "h4", "h5", "h6", "hr",
	   "noscript", "ol", "p", "pre", "table", "ul", "dd", "dt",
	   "li", "tbody", "td", "tfoot", "th", "thead", "tr"),

    KEY : {
      BACKSPACE: 8,
      ENTER: 13,
      END: 35,
      HOME: 36,
      LEFT: 37,
      UP: 38,
      RIGHT: 39,
      DOWN: 40,
      CURSOR: new Array(37, 38, 39, 40),
      DELETE: 46
    },

    NODE : {
      ELEMENT: 1,
      ATTRIBUTE: 2,
      TEXT: 3
    },
	
    /*
        Class: WYMeditor.editor
        WYMeditor editor main class, instanciated for each editor occurrence.
    */

	editor : function(elem, options) {

        /*
            Constructor: WYMeditor.editor

            Initializes main values (index, elements, paths, ...)
            and call WYMeditor.editor.init which initializes the editor.

            Parameters:

                elem - The HTML element to be replaced by the editor.
                options - The hash of options.

            Returns:

                Nothing.

            See Also:

                <WYMeditor.editor.init>
        */

        //store the instance in the INSTANCES array and store the index
        this._index = WYMeditor.INSTANCES.push(this) - 1;
        //store the element replaced by the editor
        this._element = elem;
        //store the options
        this._options = options;
        //store the element's inner value
        this._html = jQuery(elem).val();

        //store the HTML option, if any
        if(this._options.html) this._html = this._options.html;
        //get or compute the base path (where the main JS file is located)
        this._options.basePath = this._options.basePath
        || this.computeBasePath();
        //get or set the skin path (where the skin files are located)
        this._options.skinPath = this._options.skinPath
        || this._options.basePath + WYMeditor.SKINS_DEFAULT_PATH
           + this._options.skin + '/';
        //get or compute the main JS file location
        this._options.wymPath = this._options.wymPath
        || this.computeWymPath();
        //get or set the language files path
        this._options.langPath = this._options.langPath
        || this._options.basePath + WYMeditor.LANG_DEFAULT_PATH;
        //get or set the designmode iframe's base path
        this._options.iframeBasePath = this._options.iframeBasePath
        || this._options.basePath + WYMeditor.IFRAME_DEFAULT;
        //get or compute the jQuery JS file location
        this._options.jQueryPath = this._options.jQueryPath
        || this.computeJqueryPath();

        //initialize the editor instance
        this.init();
	
	}

});


/********** JQUERY **********/

/**
 * Replace an HTML element by WYMeditor
 *
 * @example jQuery(".wymeditor").wymeditor(
 *        {
 *
 *        }
 *      );
 * @desc Example description here
 * 
 * @name WYMeditor
 * @description WYMeditor is a web-based WYSIWYM XHTML editor
 * @param Hash hash A hash of parameters
 * @option Integer iExample Description here
 * @option String sExample Description here
 *
 * @type jQuery
 * @cat Plugins/WYMeditor
 * @author Jean-Francois Hovinne
 */
jQuery.fn.wymeditor = function(options) {

  options = jQuery.extend({

    html:       "",
    
    basePath:   false,
    
    skinPath:    false,
    
    wymPath:    false,
    
    iframeBasePath: false,
    
    jQueryPath: false,
    
    styles: false,
    
    stylesheet: false,
    
    skin:       "default",
    initSkin:   true,
    loadSkin:   true,

    lang:       "en",

    direction:  "ltr",

    boxHtml:   "<div class='wym_box'>"
              + "<div class='wym_area_top'>" 
              + WYMeditor.TOOLS
              + "</div>"
              + "<div class='wym_area_left'></div>"
              + "<div class='wym_area_right'>"
              + WYMeditor.CONTAINERS
              + WYMeditor.CLASSES
              + "</div>"
              + "<div class='wym_area_main'>"
              + WYMeditor.HTML
              + WYMeditor.IFRAME
              + WYMeditor.STATUS
              + "</div>"
              + "<div class='wym_area_bottom'>"
              + WYMeditor.LOGO
              + "</div>"
              + "</div>",

    logoHtml:  "<a class='wym_wymeditor_link' "
              + "href='http://www.wymeditor.org/'>WYMeditor</a>",

    iframeHtml:"<div class='wym_iframe wym_section'>"
              + "<iframe "
              + "src='"
              + WYMeditor.IFRAME_BASE_PATH
              + "wymiframe.html' "
              + "onload='this.contentWindow.parent.WYMeditor.INSTANCES["
              + WYMeditor.INDEX + "].initIframe(this)'"
              + "></iframe>"
              + "</div>",
              
    editorStyles: [],

    toolsHtml: "<div class='wym_tools wym_section'>"
              + "<h2>{Tools}</h2>"
              + "<ul>"
              + WYMeditor.TOOLS_ITEMS
              + "</ul>"
              + "</div>",
              
    toolsItemHtml:   "<li class='"
                        + WYMeditor.TOOL_CLASS
                        + "'><a href='#' name='"
                        + WYMeditor.TOOL_NAME
                        + "' title='"
                        + WYMeditor.TOOL_TITLE
                        + "'>"
                        + WYMeditor.TOOL_TITLE
                        + "</a></li>",

    toolsItems: [
        {'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong'}, 
        {'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'},
        {'name': 'Superscript', 'title': 'Superscript',
            'css': 'wym_tools_superscript'},
        {'name': 'Subscript', 'title': 'Subscript',
            'css': 'wym_tools_subscript'},
        {'name': 'InsertOrderedList', 'title': 'Ordered_List',
            'css': 'wym_tools_ordered_list'},
        {'name': 'InsertUnorderedList', 'title': 'Unordered_List',
            'css': 'wym_tools_unordered_list'},
        {'name': 'Indent', 'title': 'Indent', 'css': 'wym_tools_indent'},
        {'name': 'Outdent', 'title': 'Outdent', 'css': 'wym_tools_outdent'},
        {'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'},
        {'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'},
        {'name': 'CreateLink', 'title': 'Link', 'css': 'wym_tools_link'},
        {'name': 'Unlink', 'title': 'Unlink', 'css': 'wym_tools_unlink'},
        {'name': 'InsertImage', 'title': 'Image', 'css': 'wym_tools_image'},
        {'name': 'InsertTable', 'title': 'Table', 'css': 'wym_tools_table'},
        {'name': 'Paste', 'title': 'Paste_From_Word',
            'css': 'wym_tools_paste'},
        {'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'},
        {'name': 'Preview', 'title': 'Preview', 'css': 'wym_tools_preview'}
    ],

    containersHtml:    "<div class='wym_containers wym_section'>"
                        + "<h2>{Containers}</h2>"
                        + "<ul>"
                        + WYMeditor.CONTAINERS_ITEMS
                        + "</ul>"
                        + "</div>",
                        
    containersItemHtml:"<li class='"
                        + WYMeditor.CONTAINER_CLASS
                        + "'>"
                        + "<a href='#' name='"
                        + WYMeditor.CONTAINER_NAME
                        + "'>"
                        + WYMeditor.CONTAINER_TITLE
                        + "</a></li>",
                        
    containersItems: [
        {'name': 'P', 'title': 'Paragraph', 'css': 'wym_containers_p'},
        {'name': 'H1', 'title': 'Heading_1', 'css': 'wym_containers_h1'},
        {'name': 'H2', 'title': 'Heading_2', 'css': 'wym_containers_h2'},
        {'name': 'H3', 'title': 'Heading_3', 'css': 'wym_containers_h3'},
        {'name': 'H4', 'title': 'Heading_4', 'css': 'wym_containers_h4'},
        {'name': 'H5', 'title': 'Heading_5', 'css': 'wym_containers_h5'},
        {'name': 'H6', 'title': 'Heading_6', 'css': 'wym_containers_h6'},
        {'name': 'PRE', 'title': 'Preformatted', 'css': 'wym_containers_pre'},
        {'name': 'BLOCKQUOTE', 'title': 'Blockquote',
            'css': 'wym_containers_blockquote'},
        {'name': 'TH', 'title': 'Table_Header', 'css': 'wym_containers_th'}
    ],

    classesHtml:       "<div class='wym_classes wym_section'>"
                        + "<h2>{Classes}</h2><ul>"
                        + WYMeditor.CLASSES_ITEMS
                        + "</ul></div>",

    classesItemHtml:   "<li><a href='#' name='"
                        + WYMeditor.CLASS_NAME
                        + "'>"
                        + WYMeditor.CLASS_TITLE
                        + "</a></li>",

    classesItems:      [],

    statusHtml:        "<div class='wym_status wym_section'>"
                        + "<h2>{Status}</h2>"
                        + "</div>",

    htmlHtml:          "<div class='wym_html wym_section'>"
                        + "<h2>{Source_Code}</h2>"
                        + "<textarea class='wym_html_val'></textarea>"
                        + "</div>",

    boxSelector:       ".wym_box",
    toolsSelector:     ".wym_tools",
    toolsListSelector: " ul",
    containersSelector:".wym_containers",
    classesSelector:   ".wym_classes",
    htmlSelector:      ".wym_html",
    iframeSelector:    ".wym_iframe iframe",
    iframeBodySelector:".wym_iframe",
    statusSelector:    ".wym_status",
    toolSelector:      ".wym_tools a",
    containerSelector: ".wym_containers a",
    classSelector:     ".wym_classes a",
    htmlValSelector:   ".wym_html_val",
    
    hrefSelector:      ".wym_href",
    srcSelector:       ".wym_src",
    titleSelector:     ".wym_title",
    altSelector:       ".wym_alt",
    textSelector:      ".wym_text",
    
    rowsSelector:      ".wym_rows",
    colsSelector:      ".wym_cols",
    captionSelector:   ".wym_caption",
    summarySelector:   ".wym_summary",
    
    submitSelector:    ".wym_submit",
    cancelSelector:    ".wym_cancel",
    previewSelector:   "",
    
    dialogTypeSelector:    ".wym_dialog_type",
    dialogLinkSelector:    ".wym_dialog_link",
    dialogImageSelector:   ".wym_dialog_image",
    dialogTableSelector:   ".wym_dialog_table",
    dialogPasteSelector:   ".wym_dialog_paste",
    dialogPreviewSelector: ".wym_dialog_preview",
    
    updateSelector:    ".wymupdate",
    updateEvent:       "click",
    
    dialogFeatures:    "menubar=no,titlebar=no,toolbar=no,resizable=no"
                      + ",width=560,height=300,top=0,left=0",

    dialogHtml:      "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'"
                      + " 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>"
                      + "<html dir='"
                      + WYMeditor.DIRECTION
                      + "'><head>"
                      + "<link rel='stylesheet' type='text/css' media='screen'"
                      + " href='"
                      + WYMeditor.CSS_PATH
                      + "' />"
                      + "<title>"
                      + WYMeditor.DIALOG_TITLE
                      + "</title>"
                      + "<script type='text/javascript'"
                      + " src='"
                      + WYMeditor.JQUERY_PATH
                      + "'></script>"
                      + "<script type='text/javascript'"
                      + " src='"
                      + WYMeditor.WYM_PATH
                      + "'></script>"
                      + "</head>"
                      + WYMeditor.DIALOG_BODY
                      + "</html>",
                      
    dialogLinkHtml:  "<body class='wym_dialog wym_dialog_link'"
               + " onload='WYMeditor.INIT_DIALOG(" + WYMeditor.INDEX + ")'"
               + ">"
               + "<form>"
               + "<fieldset>"
               + "<input type='hidden' class='wym_dialog_type' value='"
               + WYMeditor.DIALOG_LINK
               + "' />"
               + "<legend>{Link}</legend>"
               + "<div class='row'>"
               + "<label>{URL}</label>"
               + "<input type='text' class='wym_href' value='' size='40' />"
               + "</div>"
               + "<div class='row'>"
               + "<label>{Title}</label>"
               + "<input type='text' class='wym_title' value='' size='40' />"
               + "</div>"
               + "<div class='row row-indent'>"
               + "<input class='wym_submit' type='button'"
               + " value='{Submit}' />"
               + "<input class='wym_cancel' type='button'"
               + "value='{Cancel}' />"
               + "</div>"
               + "</fieldset>"
               + "</form>"
               + "</body>",
    
    dialogImageHtml:  "<body class='wym_dialog wym_dialog_image'"
               + " onload='WYMeditor.INIT_DIALOG(" + WYMeditor.INDEX + ")'"
               + ">"
               + "<form>"
               + "<fieldset>"
               + "<input type='hidden' class='wym_dialog_type' value='"
               + WYMeditor.DIALOG_IMAGE
               + "' />"
               + "<legend>{Image}</legend>"
               + "<div class='row'>"
               + "<label>{URL}</label>"
               + "<input type='text' class='wym_src' value='' size='40' />"
               + "</div>"
               + "<div class='row'>"
               + "<label>{Alternative_Text}</label>"
               + "<input type='text' class='wym_alt' value='' size='40' />"
               + "</div>"
               + "<div class='row'>"
               + "<label>{Title}</label>"
               + "<input type='text' class='wym_title' value='' size='40' />"
               + "</div>"
               + "<div class='row row-indent'>"
               + "<input class='wym_submit' type='button'"
               + " value='{Submit}' />"
               + "<input class='wym_cancel' type='button'"
               + "value='{Cancel}' />"
               + "</div>"
               + "</fieldset>"
               + "</form>"
               + "</body>",
    
    dialogTableHtml:  "<body class='wym_dialog wym_dialog_table'"
               + " onload='WYMeditor.INIT_DIALOG(" + WYMeditor.INDEX + ")'"
               + ">"
               + "<form>"
               + "<fieldset>"
               + "<input type='hidden' class='wym_dialog_type' value='"
               + WYMeditor.DIALOG_TABLE
               + "' />"
               + "<legend>{Table}</legend>"
               + "<div class='row'>"
               + "<label>{Caption}</label>"
               + "<input type='text' class='wym_caption' value='' size='40' />"
               + "</div>"
               + "<div class='row'>"
               + "<label>{Summary}</label>"
               + "<input type='text' class='wym_summary' value='' size='40' />"
               + "</div>"
               + "<div class='row'>"
               + "<label>{Number_Of_Rows}</label>"
               + "<input type='text' class='wym_rows' value='3' size='3' />"
               + "</div>"
               + "<div class='row'>"
               + "<label>{Number_Of_Cols}</label>"
               + "<input type='text' class='wym_cols' value='2' size='3' />"
               + "</div>"
               + "<div class='row row-indent'>"
               + "<input class='wym_submit' type='button'"
               + " value='{Submit}' />"
               + "<input class='wym_cancel' type='button'"
               + "value='{Cancel}' />"
               + "</div>"
               + "</fieldset>"
               + "</form>"
               + "</body>",

    dialogPasteHtml:  "<body class='wym_dialog wym_dialog_paste'"
               + " onload='WYMeditor.INIT_DIALOG(" + WYMeditor.INDEX + ")'"
               + ">"
               + "<form>"
               + "<input type='hidden' class='wym_dialog_type' value='"
               + WYMeditor.DIALOG_PASTE
               + "' />"
               + "<fieldset>"
               + "<legend>{Paste_From_Word}</legend>"
               + "<div class='row'>"
               + "<textarea class='wym_text' rows='10' cols='50'></textarea>"
               + "</div>"
               + "<div class='row'>"
               + "<input class='wym_submit' type='button'"
               + " value='{Submit}' />"
               + "<input class='wym_cancel' type='button'"
               + "value='{Cancel}' />"
               + "</div>"
               + "</fieldset>"
               + "</form>"
               + "</body>",

    dialogPreviewHtml: "<body class='wym_dialog wym_dialog_preview'"
                      + " onload='WYMeditor.INIT_DIALOG(" + WYMeditor.INDEX + ")'"
                      + "></body>",
                      
    dialogStyles: [],

    stringDelimiterLeft: "{",
    stringDelimiterRight:"}",
    
    preInit: null,
    preBind: null,
    postInit: null,
    
    preInitDialog: null,
    postInitDialog: null

  }, options);

  return this.each(function() {

    new WYMeditor.editor(jQuery(this),options);
  });
};

/* @name extend
 * @description Returns the WYMeditor instance based on its index
 */
jQuery.extend({
  wymeditors: function(i) {
    return (WYMeditor.INSTANCES[i]);
  }
});


/********** WYMeditor **********/

/* @name Wymeditor
 * @description WYMeditor class
 */

/* @name init
 * @description Initializes a WYMeditor instance
 */
WYMeditor.editor.prototype.init = function() {

  //load subclass - browser specific
  //unsupported browsers: do nothing
  if (jQuery.browser.msie) {
    var WymClass = new WYMeditor.WymClassExplorer(this);
  }
  else if (jQuery.browser.mozilla) {
    var WymClass = new WYMeditor.WymClassMozilla(this);
  }
  else if (jQuery.browser.opera) {
    var WymClass = new WYMeditor.WymClassOpera(this);
  }
  else if (jQuery.browser.safari) {
    var WymClass = new WYMeditor.WymClassSafari(this);
  }
  
  if(WymClass) {
  
      if(jQuery.isFunction(this._options.preInit)) this._options.preInit(this);

      //extend the Wymeditor object
      //don't use jQuery.extend since 1.1.4
      //jQuery.extend(this, WymClass);
      for (var prop in WymClass) { this[prop] = WymClass[prop]; }

      //load wymbox
      this._box = jQuery(this._element).hide().after(this._options.boxHtml).next();

      //store the instance index in the wymbox element
      //but keep it compatible with jQuery < 1.2.3, see #122
      if( jQuery.isFunction( jQuery.fn.data ) )
        jQuery.data(this._box.get(0), WYMeditor.WYM_INDEX, this._index);
      
      var h = WYMeditor.Helper;

      //construct the iframe
      var iframeHtml = this._options.iframeHtml;
      iframeHtml = h.replaceAll(iframeHtml, WYMeditor.INDEX, this._index);
      iframeHtml = h.replaceAll(iframeHtml, WYMeditor.IFRAME_BASE_PATH, this._options.iframeBasePath);
      
      //construct wymbox
      var boxHtml = jQuery(this._box).html();
      
      boxHtml = h.replaceAll(boxHtml, WYMeditor.LOGO, this._options.logoHtml);
      boxHtml = h.replaceAll(boxHtml, WYMeditor.TOOLS, this._options.toolsHtml);
      boxHtml = h.replaceAll(boxHtml, WYMeditor.CONTAINERS,this._options.containersHtml);
      boxHtml = h.replaceAll(boxHtml, WYMeditor.CLASSES, this._options.classesHtml);
      boxHtml = h.replaceAll(boxHtml, WYMeditor.HTML, this._options.htmlHtml);
      boxHtml = h.replaceAll(boxHtml, WYMeditor.IFRAME, iframeHtml);
      boxHtml = h.replaceAll(boxHtml, WYMeditor.STATUS, this._options.statusHtml);
      
      //construct tools list
      var aTools = eval(this._options.toolsItems);
      var sTools = "";

      for(var i = 0; i < aTools.length; i++) {
        var oTool = aTools[i];
        if(oTool.name && oTool.title)
          var sTool = this._options.toolsItemHtml;
          var sTool = h.replaceAll(sTool, WYMeditor.TOOL_NAME, oTool.name);
          sTool = h.replaceAll(sTool, WYMeditor.TOOL_TITLE, this._options.stringDelimiterLeft
            + oTool.title
            + this._options.stringDelimiterRight);
          sTool = h.replaceAll(sTool, WYMeditor.TOOL_CLASS, oTool.css);
          sTools += sTool;
      }

      boxHtml = h.replaceAll(boxHtml, WYMeditor.TOOLS_ITEMS, sTools);

      //construct classes list
      var aClasses = eval(this._options.classesItems);
      var sClasses = "";

      for(var i = 0; i < aClasses.length; i++) {
        var oClass = aClasses[i];
        if(oClass.name && oClass.title)
          var sClass = this._options.classesItemHtml;
          sClass = h.replaceAll(sClass, WYMeditor.CLASS_NAME, oClass.name);
          sClass = h.replaceAll(sClass, WYMeditor.CLASS_TITLE, oClass.title);
          sClasses += sClass;
      }

      boxHtml = h.replaceAll(boxHtml, WYMeditor.CLASSES_ITEMS, sClasses);
      
      //construct containers list
      var aContainers = eval(this._options.containersItems);
      var sContainers = "";

      for(var i = 0; i < aContainers.length; i++) {
        var oContainer = aContainers[i];
        if(oContainer.name && oContainer.title)
          var sContainer = this._options.containersItemHtml;
          sContainer = h.replaceAll(sContainer, WYMeditor.CONTAINER_NAME, oContainer.name);
          sContainer = h.replaceAll(sContainer, WYMeditor.CONTAINER_TITLE,
              this._options.stringDelimiterLeft
            + oContainer.title
            + this._options.stringDelimiterRight);
          sContainer = h.replaceAll(sContainer, WYMeditor.CONTAINER_CLASS, oContainer.css);
          sContainers += sContainer;
      }

      boxHtml = h.replaceAll(boxHtml, WYMeditor.CONTAINERS_ITEMS, sContainers);

      //l10n
      boxHtml = this.replaceStrings(boxHtml);
      
      //load html in wymbox
      jQuery(this._box).html(boxHtml);
      
      //hide the html value
      jQuery(this._box).find(this._options.htmlSelector).hide();
      
      //enable the skin
      this.loadSkin();
      
    }
};

WYMeditor.editor.prototype.bindEvents = function() {

  //copy the instance
  var wym = this;
  
  //handle click event on tools buttons
  jQuery(this._box).find(this._options.toolSelector).click(function() {
    wym.exec(jQuery(this).attr(WYMeditor.NAME));
    return(false);
  });


  //handle click event on containers buttons
  jQuery(this._box).find(this._options.containerSelector).click(function() {
    wym.container(jQuery(this).attr(WYMeditor.NAME));
    return(false);
  });
  
  //handle keyup event on html value: set the editor value
  jQuery(this._box).find(this._options.htmlValSelector).keyup(function() {
    jQuery(wym._doc.body).html(jQuery(this).val());
  });
  
  //handle click event on classes buttons
  jQuery(this._box).find(this._options.classSelector).click(function() {
  
    var aClasses = eval(wym._options.classesItems);
    var sName = jQuery(this).attr(WYMeditor.NAME);
    
    var oClass = WYMeditor.Helper.findByName(aClasses, sName);
    
    if(oClass) {
      var jqexpr = oClass.expr;
      wym.toggleClass(sName, jqexpr);
    }
    return(false);
  });
  
  //handle event on update element
  jQuery(this._options.updateSelector)
    .bind(this._options.updateEvent, function() {
      wym.update();
  });
};

WYMeditor.editor.prototype.ready = function() {
  return(this._doc != null);
};


/********** METHODS **********/

/* @name box
 * @description Returns the WYMeditor container
 */
WYMeditor.editor.prototype.box = function() {
  return(this._box);
};

/* @name html
 * @description Get/Set the html value
 */
WYMeditor.editor.prototype.html = function(html) {

  if(typeof html === 'string') jQuery(this._doc.body).html(html);
  else return(jQuery(this._doc.body).html());
};

/* @name exec
 * @description Executes a button command
 */
WYMeditor.editor.prototype.exec = function(cmd) {
  
  //base function for execCommand
  //open a dialog or exec
  switch(cmd) {
    case WYMeditor.CREATE_LINK:
      var container = this.container();
      if(container || this._selected_image) this.dialog(WYMeditor.DIALOG_LINK);
    break;
    
    case WYMeditor.INSERT_IMAGE:
      this.dialog(WYMeditor.DIALOG_IMAGE);
    break;
    
    case WYMeditor.INSERT_TABLE:
      this.dialog(WYMeditor.DIALOG_TABLE);
    break;
    
    case WYMeditor.PASTE:
      this.dialog(WYMeditor.DIALOG_PASTE);
    break;
    
    case WYMeditor.TOGGLE_HTML:
      this.update();
      this.toggleHtml();

      //partially fixes #121 when the user manually inserts an image
      if(!jQuery(this._box).find(this._options.htmlSelector).is(':visible'))
        this.listen();
    break;
    
    case WYMeditor.PREVIEW:
      this.dialog(WYMeditor.PREVIEW);
    break;
    
    default:
      this._exec(cmd);
    break;
  }
};

/* @name container
 * @description Get/Set the selected container
 */
WYMeditor.editor.prototype.container = function(sType) {

  if(sType) {
  
    var container = null;
    
    if(sType.toLowerCase() == WYMeditor.TH) {
    
      container = this.container();
      
      //find the TD or TH container
      switch(container.tagName.toLowerCase()) {
      
        case WYMeditor.TD: case WYMeditor.TH:
          break;
        default:
          var aTypes = new Array(WYMeditor.TD,WYMeditor.TH);
          container = this.findUp(this.container(), aTypes);
          break;
      }
      
      //if it exists, switch
      if(container!=null) {
      
        sType = (container.tagName.toLowerCase() == WYMeditor.TD)? WYMeditor.TH: WYMeditor.TD;
        this.switchTo(container,sType);
        this.update();
      }
    } else {
  
      //set the container type
      var aTypes=new Array(WYMeditor.P,WYMeditor.H1,WYMeditor.H2,WYMeditor.H3,WYMeditor.H4,WYMeditor.H5,
      WYMeditor.H6,WYMeditor.PRE,WYMeditor.BLOCKQUOTE);
      container = this.findUp(this.container(), aTypes);
      
      if(container) {
  
        var newNode = null;
  
        //blockquotes must contain a block level element
        if(sType.toLowerCase() == WYMeditor.BLOCKQUOTE) {
        
          var blockquote = this.findUp(this.container(), WYMeditor.BLOCKQUOTE);
          
          if(blockquote == null) {
          
            newNode = this._doc.createElement(sType);
            container.parentNode.insertBefore(newNode,container);
            newNode.appendChild(container);
            this.setFocusToNode(newNode.firstChild);
            
          } else {
          
            var nodes = blockquote.childNodes;
            var lgt = nodes.length;
            var firstNode = null;
            
            if(lgt > 0) firstNode = nodes.item(0);
            for(var x=0; x<lgt; x++) {
              blockquote.parentNode.insertBefore(nodes.item(0),blockquote);
            }
            blockquote.parentNode.removeChild(blockquote);
            if(firstNode) this.setFocusToNode(firstNode);
          }
        }
        
        else this.switchTo(container,sType);
      
        this.update();
      }
    }
  }
  else return(this.selected());
};

/* @name toggleClass
 * @description Toggles class on selected element, or one of its parents
 */
WYMeditor.editor.prototype.toggleClass = function(sClass, jqexpr) {

  var container = (this._selected_image
                    ? this._selected_image
                    : jQuery(this.selected()));
  container = jQuery(container).parentsOrSelf(jqexpr);
  jQuery(container).toggleClass(sClass);

  if(!jQuery(container).attr(WYMeditor.CLASS)) jQuery(container).removeAttr(this._class);

};

/* @name findUp
 * @description Returns the first parent or self container, based on its type
 */
WYMeditor.editor.prototype.findUp = function(node, filter) {

  //filter is a string or an array of strings

  if(node) {

      var tagname = node.tagName.toLowerCase();
      
      if(typeof(filter) == WYMeditor.STRING) {
    
        while(tagname != filter && tagname != WYMeditor.BODY) {
        
          node = node.parentNode;
          tagname = node.tagName.toLowerCase();
        }
      
      } else {
      
        var bFound = false;
        
        while(!bFound && tagname != WYMeditor.BODY) {
          for(var i = 0; i < filter.length; i++) {
            if(tagname == filter[i]) {
              bFound = true;
              break;
            }
          }
          if(!bFound) {
            node = node.parentNode;
            tagname = node.tagName.toLowerCase();
          }
        }
      }
      
      if(tagname != WYMeditor.BODY) return(node);
      else return(null);
      
  } else return(null);
};

/* @name switchTo
 * @description Switch the node's type
 */
WYMeditor.editor.prototype.switchTo = function(node,sType) {

  var newNode = this._doc.createElement(sType);
  var html = jQuery(node).html();
  node.parentNode.replaceChild(newNode,node);
  jQuery(newNode).html(html);
  this.setFocusToNode(newNode);
};

WYMeditor.editor.prototype.replaceStrings = function(sVal) {
  //check if the language file has already been loaded
  //if not, get it via a synchronous ajax call
  if(!WYMeditor.STRINGS[this._options.lang]) {
    try {
      eval(jQuery.ajax({url:this._options.langPath
        + this._options.lang + '.js', async:false}).responseText);
    } catch(e) {
        WYMeditor.console.error("WYMeditor: error while parsing language file.");
        return sVal;
    }
  }

  //replace all the strings in sVal and return it
  for (var key in WYMeditor.STRINGS[this._options.lang]) {
    sVal = WYMeditor.Helper.replaceAll(sVal, this._options.stringDelimiterLeft + key 
    + this._options.stringDelimiterRight,
    WYMeditor.STRINGS[this._options.lang][key]);
  };
  return(sVal);
};

WYMeditor.editor.prototype.encloseString = function(sVal) {

  return(this._options.stringDelimiterLeft
    + sVal
    + this._options.stringDelimiterRight);
};

/* @name status
 * @description Prints a status message
 */
WYMeditor.editor.prototype.status = function(sMessage) {

  //print status message
  jQuery(this._box).find(this._options.statusSelector).html(sMessage);
};

/* @name update
 * @description Updates the element and textarea values
 */
WYMeditor.editor.prototype.update = function() {
/*
  var html = this.xhtml();
  jQuery(this._element).val(html);
  jQuery(this._box).find(this._options.htmlValSelector).val(html);
*/
};

/* @name dialog
 * @description Opens a dialog box
 */
WYMeditor.editor.prototype.dialog = function( dialogType, bodyHtml ) {
  
  var wDialog = window.open(
    '',
    'dialog',
    this._wym._options.dialogFeatures);

  if(wDialog) {

    var sBodyHtml = "";
    
    switch( dialogType ) {

      case(WYMeditor.DIALOG_LINK):
        sBodyHtml = this._options.dialogLinkHtml;
      break;
      case(WYMeditor.DIALOG_IMAGE):
        sBodyHtml = this._options.dialogImageHtml;
      break;
      case(WYMeditor.DIALOG_TABLE):
        sBodyHtml = this._options.dialogTableHtml;
      break;
      case(WYMeditor.DIALOG_PASTE):
        sBodyHtml = this._options.dialogPasteHtml;
      break;
      case(WYMeditor.PREVIEW):
        sBodyHtml = this._options.dialogPreviewHtml;
      break;

      default:
        sBodyHtml = bodyHtml;
    }
    
    var h = WYMeditor.Helper;

    //construct the dialog
    var dialogHtml = this._options.dialogHtml;
    dialogHtml = h.replaceAll(dialogHtml, WYMeditor.BASE_PATH, this._options.basePath);
    dialogHtml = h.replaceAll(dialogHtml, WYMeditor.DIRECTION, this._options.direction);
    dialogHtml = h.replaceAll(dialogHtml, WYMeditor.CSS_PATH, this._options.skinPath + WYMeditor.SKINS_DEFAULT_CSS);
    dialogHtml = h.replaceAll(dialogHtml, WYMeditor.WYM_PATH, this._options.wymPath);
    dialogHtml = h.replaceAll(dialogHtml, WYMeditor.JQUERY_PATH, this._options.jQueryPath);
    dialogHtml = h.replaceAll(dialogHtml, WYMeditor.DIALOG_TITLE, this.encloseString( dialogType ));
    dialogHtml = h.replaceAll(dialogHtml, WYMeditor.DIALOG_BODY, sBodyHtml);
    dialogHtml = h.replaceAll(dialogHtml, WYMeditor.INDEX, this._index);
      
    dialogHtml = this.replaceStrings(dialogHtml);
    
    var doc = wDialog.document;
    doc.write(dialogHtml);
    doc.close();
  }
};

/* @name toggleHtml
 * @description Shows/Hides the HTML
 */
WYMeditor.editor.prototype.toggleHtml = function() {
  jQuery(this._box).find(this._options.htmlSelector).toggle();
};

WYMeditor.editor.prototype.uniqueStamp = function() {
	var now = new Date();
	return("wym-" + now.getTime());
};

WYMeditor.editor.prototype.paste = function(sData) {

  var sTmp;
  var container = this.selected();
	
  //split the data, using double newlines as the separator
  var aP = sData.split(this._newLine + this._newLine);
  var rExp = new RegExp(this._newLine, "g");

  //add a P for each item
  if(container && container.tagName.toLowerCase() != WYMeditor.BODY) {
    for(x = aP.length - 1; x >= 0; x--) {
        sTmp = aP[x];
        //simple newlines are replaced by a break
        sTmp = sTmp.replace(rExp, "<br />");
        jQuery(container).after("<p>" + sTmp + "</p>");
    }
  } else {
    for(x = 0; x < aP.length; x++) {
        sTmp = aP[x];
        //simple newlines are replaced by a break
        sTmp = sTmp.replace(rExp, "<br />");
        jQuery(this._doc.body).append("<p>" + sTmp + "</p>");
    }
  
  }
};

WYMeditor.editor.prototype.insert = function(html) {
    // Do we have a selection?
    if (this._iframe.contentWindow.getSelection().focusNode != null) {
        // Overwrite selection with provided html
        this._exec( WYMeditor.INSERT_HTML, html);
    } else {
        // Fall back to the internal paste function if there's no selection
        this.paste(html)
    }
};

WYMeditor.editor.prototype.wrap = function(left, right) {
    // Do we have a selection?
    if (this._iframe.contentWindow.getSelection().focusNode != null) {
        // Wrap selection with provided html
        this._exec( WYMeditor.INSERT_HTML, left + this._iframe.contentWindow.getSelection().toString() + right);
    }
};

WYMeditor.editor.prototype.unwrap = function() {
    // Do we have a selection?
    if (this._iframe.contentWindow.getSelection().focusNode != null) {
        // Unwrap selection
        this._exec( WYMeditor.INSERT_HTML, this._iframe.contentWindow.getSelection().toString() );
    }
};

WYMeditor.editor.prototype.addCssRules = function(doc, aCss) {
  var styles = doc.styleSheets[0];
  if(styles) {
    for(var i = 0; i < aCss.length; i++) {
      var oCss = aCss[i];
      if(oCss.name && oCss.css) this.addCssRule(styles, oCss);
    }
  }
};

/********** CONFIGURATION **********/

WYMeditor.editor.prototype.computeBasePath = function() {
  return jQuery(jQuery.grep(jQuery('script'), function(s){
    return (s.src && s.src.match(/jquery\.wymeditor(\.pack){0,1}\.js(\?.*)?$/ ))
  })).attr('src').replace(/jquery\.wymeditor(\.pack){0,1}\.js(\?.*)?$/, '');
};

WYMeditor.editor.prototype.computeWymPath = function() {
  return jQuery(jQuery.grep(jQuery('script'), function(s){
    return (s.src && s.src.match(/jquery\.wymeditor(\.pack){0,1}\.js(\?.*)?$/ ))
  })).attr('src');
};

WYMeditor.editor.prototype.computeJqueryPath = function() {
  return jQuery(jQuery.grep(jQuery('script'), function(s){
    return (s.src && s.src.match(/jquery(-(.*)){0,1}(\.pack){0,1}\.js(\?.*)?$/ ))
  })).attr('src');
};

WYMeditor.editor.prototype.computeCssPath = function() {
  return jQuery(jQuery.grep(jQuery('link'), function(s){
   return (s.href && s.href.match(/wymeditor\/skins\/(.*)screen\.css(\?.*)?$/ ))
  })).attr('href');
};

/********** EVENTS **********/

WYMeditor.editor.prototype.listen = function() {

  //don't use jQuery.find() on the iframe body
  //because of MSIE + jQuery + expando issue (#JQ1143)
  //jQuery(this._doc.body).find("*").bind("mouseup", this.mouseup);
  
  jQuery(this._doc.body).bind("mousedown", this.mousedown);
  var images = this._doc.body.getElementsByTagName("img");
  for(var i=0; i < images.length; i++) {
    jQuery(images[i]).bind("mousedown", this.mousedown);
  }
};

WYMeditor.editor.prototype.mousedown = function(evt) {
  
  var wym = WYMeditor.INSTANCES[this.ownerDocument.title];
  wym._selected_image = (this.tagName.toLowerCase() == WYMeditor.IMG) ? this : null;
  evt.stopPropagation();
};

/********** SKINS **********/

/*
 * Function: WYMeditor.loadCss
 *      Loads a stylesheet in the document.
 *
 * Parameters:
 *      href - The CSS path.
 */
WYMeditor.loadCss = function(href) {
    
    var link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = href;

    var head = jQuery('head').get(0);
    head.appendChild(link);
};

/*
 *  Function: WYMeditor.editor.loadSkin
 *      Loads the skin CSS and initialization script (if needed).
 */
WYMeditor.editor.prototype.loadSkin = function() {

    //does the user want to automatically load the CSS (default: yes)?
    //we also test if it hasn't been already loaded by another instance
    //see below for a better (second) test
    if(this._options.loadSkin && !WYMeditor.SKINS[this._options.skin]) {

        //check if it hasn't been already loaded
        //so we don't load it more than once
        //(we check the existing <link> elements)

        var found = false;
        var rExp = new RegExp(this._options.skin
             + '\/' + WYMeditor.SKINS_DEFAULT_CSS + '$');

        jQuery('link').each( function() {
            if(this.href.match(rExp)) found = true;
        });

        //load it, using the skin path
        if(!found) WYMeditor.loadCss( this._options.skinPath
            + WYMeditor.SKINS_DEFAULT_CSS );
    }

    //put the classname (ex. wym_skin_default) on wym_box
    jQuery(this._box).addClass( "wym_skin_" + this._options.skin );

    //does the user want to use some JS to initialize the skin (default: yes)?
    //also check if it hasn't already been loaded by another instance
    if(this._options.initSkin && !WYMeditor.SKINS[this._options.skin]) {

        eval(jQuery.ajax({url:this._options.skinPath
            + WYMeditor.SKINS_DEFAULT_JS, async:false}).responseText);
    }

    //init the skin, if needed
    if(WYMeditor.SKINS[this._options.skin]
    && WYMeditor.SKINS[this._options.skin].init)
       WYMeditor.SKINS[this._options.skin].init(this);

};


/********** DIALOGS **********/

WYMeditor.INIT_DIALOG = function(index) {

  var wym = window.opener.WYMeditor.INSTANCES[index];
  var doc = window.document;
  var selected = wym.selected();
  var dialogType = jQuery(wym._options.dialogTypeSelector).val();
  var sStamp = wym.uniqueStamp();

  switch(dialogType) {

  case WYMeditor.DIALOG_LINK:
    //ensure that we select the link to populate the fields
    if(selected && selected.tagName && selected.tagName.toLowerCase != WYMeditor.A)
      selected = jQuery(selected).parentsOrSelf(WYMeditor.A);

    //fix MSIE selection if link image has been clicked
    if(!selected && wym._selected_image)
      selected = jQuery(wym._selected_image).parentsOrSelf(WYMeditor.A);
  break;

  }

  //pre-init functions
  if(jQuery.isFunction(wym._options.preInitDialog))
    wym._options.preInitDialog(wym,window);

  //add css rules from options
  var styles = doc.styleSheets[0];
  var aCss = eval(wym._options.dialogStyles);

  wym.addCssRules(doc, aCss);

  //auto populate fields if selected container (e.g. A)
  if(selected) {
    jQuery(wym._options.hrefSelector).val(jQuery(selected).attr(WYMeditor.HREF));
    jQuery(wym._options.srcSelector).val(jQuery(selected).attr(WYMeditor.SRC));
    jQuery(wym._options.titleSelector).val(jQuery(selected).attr(WYMeditor.TITLE));
    jQuery(wym._options.altSelector).val(jQuery(selected).attr(WYMeditor.ALT));
  }

  //auto populate image fields if selected image
  if(wym._selected_image) {
    jQuery(wym._options.dialogImageSelector + " " + wym._options.srcSelector)
      .val(jQuery(wym._selected_image).attr(WYMeditor.SRC));
    jQuery(wym._options.dialogImageSelector + " " + wym._options.titleSelector)
      .val(jQuery(wym._selected_image).attr(WYMeditor.TITLE));
    jQuery(wym._options.dialogImageSelector + " " + wym._options.altSelector)
      .val(jQuery(wym._selected_image).attr(WYMeditor.ALT));
  }

  jQuery(wym._options.dialogLinkSelector + " "
    + wym._options.submitSelector).click(function() {

      var sUrl = jQuery(wym._options.hrefSelector).val();
      if(sUrl.length > 0) {

        wym._exec(WYMeditor.CREATE_LINK, sStamp);

        jQuery("a[@href=" + sStamp + "]", wym._doc.body)
            .attr(WYMeditor.HREF, sUrl)
            .attr(WYMeditor.TITLE, jQuery(wym._options.titleSelector).val());

      }
      window.close();
  });

  jQuery(wym._options.dialogImageSelector + " "
    + wym._options.submitSelector).click(function() {

      var sUrl = jQuery(wym._options.srcSelector).val();
      if(sUrl.length > 0) {

        wym._exec(WYMeditor.INSERT_IMAGE, sStamp);

        jQuery("img[@src=" + sStamp + "]", wym._doc.body)
            .attr(WYMeditor.SRC, sUrl)
            .attr(WYMeditor.TITLE, jQuery(wym._options.titleSelector).val())
            .attr(WYMeditor.ALT, jQuery(wym._options.altSelector).val());
      }
      window.close();
  });

  jQuery(wym._options.dialogTableSelector + " "
    + wym._options.submitSelector).click(function() {

      var iRows = jQuery(wym._options.rowsSelector).val();
      var iCols = jQuery(wym._options.colsSelector).val();

      if(iRows > 0 && iCols > 0) {

        var table = wym._doc.createElement(WYMeditor.TABLE);
        var newRow = null;
		var newCol = null;

		var sCaption = jQuery(wym._options.captionSelector).val();

		//we create the caption
		var newCaption = table.createCaption();
		newCaption.innerHTML = sCaption;

		//we create the rows and cells
		for(x=0; x<iRows; x++) {
			newRow = table.insertRow(x);
			for(y=0; y<iCols; y++) {newRow.insertCell(y);}
		}

        //set the summary attr
        jQuery(table).attr('summary',
            jQuery(wym._options.summarySelector).val());

        //append the table after the selected container
        var node = jQuery(wym.findUp(wym.container(),
          WYMeditor.MAIN_CONTAINERS)).get(0);
        if(!node || !node.parentNode) jQuery(wym._doc.body).append(table);
        else jQuery(node).after(table);
      }
      window.close();
  });

  jQuery(wym._options.dialogPasteSelector + " "
    + wym._options.submitSelector).click(function() {

      var sText = jQuery(wym._options.textSelector).val();
      wym.paste(sText);
      window.close();
  });

  //cancel button
  jQuery(wym._options.cancelSelector).mousedown(function() {
    window.close();
  });

  //pre-init functions
  if(jQuery.isFunction(wym._options.postInitDialog))
    wym._options.postInitDialog(wym,window);

};


/********** HELPERS **********/

// Returns true if it is a text node with whitespaces only
jQuery.fn.isPhantomNode = function() {
  if (this[0].nodeType == 3)
    return !(/[^\t\n\r ]/.test(this[0].data));

  return false;
};

WYMeditor.isPhantomNode = function(n) {
  if (n.nodeType == 3)
    return !(/[^\t\n\r ]/.test(n.data));

  return false;
};

WYMeditor.isPhantomString = function(str) {
    return !(/[^\t\n\r ]/.test(str));
};

// Returns the Parents or the node itself
// jqexpr = a jQuery expression
jQuery.fn.parentsOrSelf = function(jqexpr) {
  var n = this;

  if (n[0].nodeType == 3)
    n = n.parents().slice(0,1);

//  if (n.is(jqexpr)) // XXX should work, but doesn't (probably a jQuery bug)
  if (n.filter(jqexpr).size() == 1)
    return n;
  else
    return n.parents(jqexpr).slice(0,1);
};

// String & array helpers

WYMeditor.Helper = {

    //replace all instances of 'old' by 'rep' in 'str' string
    replaceAll: function(str, old, rep) {
        var rExp = new RegExp(old, "g");
        return(str.replace(rExp, rep));
    },

    //insert 'inserted' at position 'pos' in 'str' string
    insertAt: function(str, inserted, pos) {
        return(str.substr(0,pos) + inserted + str.substring(pos));
    },

    //trim 'str' string
    trim: function(str) {
        return str.replace(/^(\s*)|(\s*)$/gm,'');
    },

    //return true if 'arr' array contains 'elem', or false
    contains: function(arr, elem) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] === elem) return true;
        }
        return false;
    },

    //return 'item' position in 'arr' array, or -1
    indexOf: function(arr, item) {
        var ret=-1;
        for(var i = 0; i < arr.length; i++) {
            if (arr[i] == item) {
                ret = i;
                break;
            }
        }
	    return(ret);
    },

    //return 'item' object in 'arr' array, checking its 'name' property, or null
    findByName: function(arr, name) {
        for(var i = 0; i < arr.length; i++) {
            var item = arr[i];
            if(item.name == name) return(item);
        }
        return(null);
    }
};


/*
 * WYMeditor : what you see is What You Mean web-based editor
 * Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
 * Dual licensed under the MIT (MIT-license.txt)
 * and GPL (GPL-license.txt) licenses.
 *
 * For further information visit:
 *        http://www.wymeditor.org/
 *
 * File Name:
 *        jquery.wymeditor.explorer.js
 *        MSIE specific class and functions.
 *        See the documentation for more info.
 *
 * File Authors:
 *        Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
 *        Bermi Ferrer (wymeditor a-t bermi dotorg)
 *        Frédéric Palluel-Lafleur (fpalluel a-t gmail dotcom)
 *        Jonatan Lundin (jonatan.lundin _at_ gmail.com)
 */

WYMeditor.WymClassExplorer = function(wym) {

    this._wym = wym;
    this._class = "className";
    this._newLine = "\r\n";
};

WYMeditor.WymClassExplorer.prototype.initIframe = function(iframe) {

    //This function is executed twice, though it is called once!
    //But MSIE needs that, otherwise designMode won't work.
    //Weird.
    
    this._iframe = iframe;
    this._doc = iframe.contentWindow.document;
    
    //add css rules from options
    var styles = this._doc.styleSheets[0];
    var aCss = eval(this._options.editorStyles);

    this.addCssRules(this._doc, aCss);

    this._doc.title = this._wym._index;

    //set the text direction
    //jQuery('html', this._doc).attr('dir', this._options.direction);
    
    //init html value
    jQuery(this._doc.body).html(this._wym._html);
    
    //handle events
    var wym = this;
    
    this._doc.body.onfocus = function(){
      wym._doc.designMode = "on";
      wym._doc = iframe.contentWindow.document;
    };

    this._doc.onbeforedeactivate = function() {
      wym.saveCaret();
    };

    this._doc.onkeyup = function() {
      wym.saveCaret();
      wym.keyup();
    };
    this._doc.onclick = function() {wym.saveCaret();};
    
    this._doc.body.onbeforepaste = function() {
      wym._iframe.contentWindow.event.returnValue = false;
    };
    
    this._doc.body.onpaste = function() {
      wym._iframe.contentWindow.event.returnValue = false;
      wym.paste(window.clipboardData.getData("Text"));
    };
    
    //callback can't be executed twice, so we check
    if(this._initialized) {
      
      //pre-bind functions
      if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
      
      //bind external events
      this._wym.bindEvents();
      
      //post-init functions
      if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
      
      //add event listeners to doc elements, e.g. images
      this.listen();
    }
    
    this._initialized = true;
    
    //init designMode
    this._doc.designMode="on";
    try{
        // (bermi's note) noticed when running unit tests on IE6
        // Is this really needed, it trigger an unexisting property on IE6
        this._doc = iframe.contentWindow.document; 
    }catch(e){}
};

WYMeditor.WymClassExplorer.prototype._exec = function(cmd,param) {

    //console.log("insert");
    if(this._doc.caretPos){
      this._doc.caretPos.select();
    }

    switch(cmd) {
    
    case WYMeditor.INDENT: case WYMeditor.OUTDENT:
    
        var container = this.findUp(this.container(), WYMeditor.LI);
        if(container)
            this._doc.execCommand(cmd);
    break;
    default:
        if(param) this._doc.execCommand(cmd,false,param);
        else this._doc.execCommand(cmd);
    break;
	}
    
    this.listen();
};

WYMeditor.WymClassExplorer.prototype.selected = function() {

    var caretPos = this._iframe.contentWindow.document.caretPos;
        if(caretPos!=null) {
            if(caretPos.parentElement!=undefined)
              return(caretPos.parentElement());
        }
};

WYMeditor.WymClassExplorer.prototype.saveCaret = function() {

    this._doc.caretPos = this._doc.selection.createRange();
};

WYMeditor.WymClassExplorer.prototype.addCssRule = function(styles, oCss) {

    styles.addRule(oCss.name, oCss.css);
};

WYMeditor.WymClassExplorer.prototype.insert = function(html) {

    // Get the current selection
    var range = this._doc.selection.createRange();

    // Check if the current selection is inside the editor
    if ( jQuery(range.parentElement()).parents( this._options.iframeBodySelector ).is('*') ) {
        try {
            // Overwrite selection with provided html
            range.pasteHTML(html);
        } catch (e) { }
    } else {
        // Fall back to the internal paste function if there's no selection
        this.paste(html);
    }
};

WYMeditor.WymClassExplorer.prototype.wrap = function(left, right) {

    // Get the current selection
    var range = this._options.createRange();

    // Check if the current selection is inside the editor
    if ( jQuery(range.parentElement()).parents( this._options.iframeBodySelector ).is('*') ) {
        try {
            // Overwrite selection with provided html
            range.pasteHTML(left + range.text + right);
        } catch (e) { }
    }
};

WYMeditor.WymClassExplorer.prototype.unwrap = function() {

    // Get the current selection
    var range = this._doc.selection.createRange();

    // Check if the current selection is inside the editor
    if ( jQuery(range.parentElement()).parents( this._options.iframeBodySelector ).is('*') ) {
        try {
            // Unwrap selection
            var text = range.text;
            this._exec( 'Cut' );
            range.pasteHTML( text );
        } catch (e) { }
    }
};

//keyup handler
WYMeditor.WymClassExplorer.prototype.keyup = function() {
  this._selected_image = null;
};

WYMeditor.WymClassExplorer.prototype.setFocusToNode = function(node) {
    var range = this._doc.selection.createRange();
    range.moveToElementText(node);
    range.collapse(false);
    range.move('character',-1);
    range.select();
    node.focus();
};

/*
 * WYMeditor : what you see is What You Mean web-based editor
 * Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
 * Dual licensed under the MIT (MIT-license.txt)
 * and GPL (GPL-license.txt) licenses.
 *
 * For further information visit:
 *        http://www.wymeditor.org/
 *
 * File Name:
 *        jquery.wymeditor.mozilla.js
 *        Gecko specific class and functions.
 *        See the documentation for more info.
 *
 * File Authors:
 *        Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
 *        Volker Mische (vmx a-t gmx dotde)
 *        Bermi Ferrer (wymeditor a-t bermi dotorg)
 *        Frédéric Palluel-Lafleur (fpalluel a-t gmail dotcom)
 */

WYMeditor.WymClassMozilla = function(wym) {

    this._wym = wym;
    this._class = "class";
    this._newLine = "\n";
};

WYMeditor.WymClassMozilla.prototype.initIframe = function(iframe) {

    this._iframe = iframe;
    this._doc = iframe.contentDocument;
    
    //add css rules from options
    
    var styles = this._doc.styleSheets[0];    
    var aCss = eval(this._options.editorStyles);
    
    this.addCssRules(this._doc, aCss);

    this._doc.title = this._wym._index;

    //set the text direction
    jQuery('html', this._doc).attr('dir', this._options.direction);
    
    //init html value
    this.html(this._wym._html);
    
    //init designMode
    this.enableDesignMode();
    
    //pre-bind functions
    if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
    
    //bind external events
    this._wym.bindEvents();
    
    //bind editor keydown events
    jQuery(this._doc).bind("keydown", this.keydown);
    
    //bind editor keyup events
    jQuery(this._doc).bind("keyup", this.keyup);
    
    //bind editor focus events (used to reset designmode - Gecko bug)
    jQuery(this._doc).bind("focus", this.enableDesignMode);
    
    //post-init functions
    if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
    
    //add event listeners to doc elements, e.g. images
    this.listen();
};

/* @name html
 * @description Get/Set the html value
 */
WYMeditor.WymClassMozilla.prototype.html = function(html) {

  if(typeof html === 'string') {
  
    //disable designMode
    try { this._doc.designMode = "off"; } catch(e) { };
    
    //replace em by i and strong by bold
    //(designMode issue)
    html = html.replace(/<em([^>]*)>/gi, "<i$1>")
      .replace(/<\/em>/gi, "</i>")
      .replace(/<strong([^>]*)>/gi, "<b$1>")
      .replace(/<\/strong>/gi, "</b>");
    
    //update the html body
    jQuery(this._doc.body).html(html);
    
    //re-init designMode
    this.enableDesignMode();
  }
  else return(jQuery(this._doc.body).html());
};

WYMeditor.WymClassMozilla.prototype._exec = function(cmd,param) {

    if(!this.selected()) return(false);

    switch(cmd) {
    
    case WYMeditor.INDENT: case WYMeditor.OUTDENT:
    
        var focusNode = this.selected();    
        var sel = this._iframe.contentWindow.getSelection();
        var anchorNode = sel.anchorNode;
        if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;
        
        focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
        anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);
        
        if(focusNode && focusNode == anchorNode
          && focusNode.tagName.toLowerCase() == WYMeditor.LI) {

            var ancestor = focusNode.parentNode.parentNode;

            if(focusNode.parentNode.childNodes.length>1
              || ancestor.tagName.toLowerCase() == WYMeditor.OL
              || ancestor.tagName.toLowerCase() == WYMeditor.UL)
                this._doc.execCommand(cmd,'',null);
        }

    break;
    
    default:

        if(param) this._doc.execCommand(cmd,'',param);
        else this._doc.execCommand(cmd,'',null);
    }
    
    //set to P if parent = BODY
    var container = this.selected();
    if(container.tagName.toLowerCase() == WYMeditor.BODY)
        this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
    
    //add event handlers on doc elements

    this.listen();
};

/* @name selected
 * @description Returns the selected container
 */
WYMeditor.WymClassMozilla.prototype.selected = function() {

    var sel = this._iframe.contentWindow.getSelection();
    var node = sel.focusNode;
    if(node) {
        if(node.nodeName == "#text") return(node.parentNode);
        else return(node);
    } else return(null);
};

WYMeditor.WymClassMozilla.prototype.addCssRule = function(styles, oCss) {

    styles.insertRule(oCss.name + " {" + oCss.css + "}",
        styles.cssRules.length);
};


//keydown handler, mainly used for keyboard shortcuts
WYMeditor.WymClassMozilla.prototype.keydown = function(evt) {
  
  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];
  
  if(evt.ctrlKey){
    if(evt.keyCode == 66){
      //CTRL+b => STRONG
      wym._exec(WYMeditor.BOLD);
      return false;
    }
    if(evt.keyCode == 73){
      //CTRL+i => EMPHASIS
      wym._exec(WYMeditor.ITALIC);
      return false;
    }
  }
};

//keyup handler, mainly used for cleanups
WYMeditor.WymClassMozilla.prototype.keyup = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];
  
  wym._selected_image = null;
  var container = null;

  if(evt.keyCode == 13 && !evt.shiftKey) {
  
    //RETURN key
    //cleanup <br><br> between paragraphs
    jQuery(wym._doc.body).children(WYMeditor.BR).remove();
    
    //fix PRE bug #73
    container = wym.selected();
    if(container && container.tagName.toLowerCase() == WYMeditor.PRE)
        wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P); //create P after PRE
  }
  
  else if(evt.keyCode != 8
       && evt.keyCode != 17
       && evt.keyCode != 46
       && evt.keyCode != 224
       && !evt.metaKey
       && !evt.ctrlKey) {
      
    //NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
    //text nodes replaced by P
    
    container = wym.selected();
    var name = container.tagName.toLowerCase();

    //fix forbidden main containers
    if(
      name == "strong" ||
      name == "b" ||
      name == "em" ||
      name == "i" ||
      name == "sub" ||
      name == "sup" ||
      name == "a"

    ) name = container.parentNode.tagName.toLowerCase();

    if(name == WYMeditor.BODY) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
  }
};

WYMeditor.WymClassMozilla.prototype.enableDesignMode = function() {
    if(this.designMode == "off") {
      try {
        this.designMode = "on";
        this.execCommand("styleWithCSS", '', false);
      } catch(e) { }
    }
};

WYMeditor.WymClassMozilla.prototype.setFocusToNode = function(node) {
    var range = document.createRange();
    range.selectNode(node);
    var selected = this._iframe.contentWindow.getSelection();
    selected.addRange(range);
    selected.collapse(node, node.childNodes.length);
    this._iframe.contentWindow.focus();
};

/*
 * WYMeditor : what you see is What You Mean web-based editor
 * Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
 * Dual licensed under the MIT (MIT-license.txt)
 * and GPL (GPL-license.txt) licenses.
 *
 * For further information visit:
 *        http://www.wymeditor.org/
 *
 * File Name:
 *        jquery.wymeditor.opera.js
 *        Opera specific class and functions.
 *        See the documentation for more info.
 *
 * File Authors:
 *        Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
 */

WYMeditor.WymClassOpera = function(wym) {

    this._wym = wym;
    this._class = "class";
    this._newLine = "\r\n";
};

WYMeditor.WymClassOpera.prototype.initIframe = function(iframe) {

    this._iframe = iframe;
    this._doc = iframe.contentWindow.document;
    
    //add css rules from options
    var styles = this._doc.styleSheets[0];    
    var aCss = eval(this._options.editorStyles);
    
    this.addCssRules(this._doc, aCss);

    this._doc.title = this._wym._index;

    //set the text direction
    jQuery('html', this._doc).attr('dir', this._options.direction);
    
    //init designMode
    this._doc.designMode = "on";

    //init html value
    this.html(this._wym._html);
    
    //pre-bind functions
    if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
    
    //bind external events
    this._wym.bindEvents();
    
    //bind editor keydown events
    jQuery(this._doc).bind("keydown", this.keydown);
    
    //bind editor events
    jQuery(this._doc).bind("keyup", this.keyup);
    
    //post-init functions
    if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
    
    //add event listeners to doc elements, e.g. images
    this.listen();
};

WYMeditor.WymClassOpera.prototype._exec = function(cmd,param) {

    if(param) this._doc.execCommand(cmd,false,param);
    else this._doc.execCommand(cmd);
    
    this.listen();
};

WYMeditor.WymClassOpera.prototype.selected = function() {

    var sel=this._iframe.contentWindow.getSelection();
    var node=sel.focusNode;
    if(node) {
        if(node.nodeName=="#text")return(node.parentNode);
        else return(node);
    } else return(null);
};

WYMeditor.WymClassOpera.prototype.addCssRule = function(styles, oCss) {

    styles.insertRule(oCss.name + " {" + oCss.css + "}",
        styles.cssRules.length);
};

//keydown handler
WYMeditor.WymClassOpera.prototype.keydown = function(evt) {
  
  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];
  var sel = wym._iframe.contentWindow.getSelection();
  startNode = sel.getRangeAt(0).startContainer;

  //Get a P instead of no container
  if(!jQuery(startNode).parentsOrSelf(
                WYMeditor.MAIN_CONTAINERS.join(","))[0]
      && !jQuery(startNode).parentsOrSelf('li')
      && evt.keyCode != WYMeditor.KEY.ENTER
      && evt.keyCode != WYMeditor.KEY.LEFT
      && evt.keyCode != WYMeditor.KEY.UP
      && evt.keyCode != WYMeditor.KEY.RIGHT
      && evt.keyCode != WYMeditor.KEY.DOWN
      && evt.keyCode != WYMeditor.KEY.BACKSPACE
      && evt.keyCode != WYMeditor.KEY.DELETE)
      wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);

};

//keyup handler
WYMeditor.WymClassOpera.prototype.keyup = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];
  wym._selected_image = null;
};

// TODO: implement me
WYMeditor.WymClassOpera.prototype.setFocusToNode = function(node) {

};

/*
 * WYMeditor : what you see is What You Mean web-based editor
 * Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
 * Dual licensed under the MIT (MIT-license.txt)
 * and GPL (GPL-license.txt) licenses.
 *
 * For further information visit:
 *        http://www.wymeditor.org/
 *
 * File Name:
 *        jquery.wymeditor.safari.js
 *        Safari specific class and functions.
 *        See the documentation for more info.
 *
 * File Authors:
 *        Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
 *        Scott Lewis (lewiscot a-t gmail dotcom)
 */

WYMeditor.WymClassSafari = function(wym) {

    this._wym = wym;
    this._class = "class";
    this._newLine = "\n";
};

WYMeditor.WymClassSafari.prototype.initIframe = function(iframe) {

    this._iframe = iframe;
    this._doc = iframe.contentDocument;
    
    //add css rules from options
    
    var styles = this._doc.styleSheets[0];    
    var aCss = eval(this._options.editorStyles);
    
    this.addCssRules(this._doc, aCss);

    this._doc.title = this._wym._index;

    //set the text direction
    jQuery('html', this._doc).attr('dir', this._options.direction);

    //init designMode
    this._doc.designMode = "on";
    
    //init html value
    this.html(this._wym._html);
    
    //pre-bind functions
    if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
    
    //bind external events
    this._wym.bindEvents();
    
    //bind editor keydown events
    jQuery(this._doc).bind("keydown", this.keydown);
    
    //bind editor keyup events
    jQuery(this._doc).bind("keyup", this.keyup);
    
    //post-init functions
    if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
    
    //add event listeners to doc elements, e.g. images
    this.listen();
};

WYMeditor.WymClassSafari.prototype._exec = function(cmd,param) {

    if(!this.selected()) return(false);

    switch(cmd) {
    
    case WYMeditor.INDENT: case WYMeditor.OUTDENT:
    
        var focusNode = this.selected();    
        var sel = this._iframe.contentWindow.getSelection();
        var anchorNode = sel.anchorNode;
        if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;
        
        focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
        anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);
        
        if(focusNode && focusNode == anchorNode
          && focusNode.tagName.toLowerCase() == WYMeditor.LI) {

            var ancestor = focusNode.parentNode.parentNode;

            if(focusNode.parentNode.childNodes.length>1
              || ancestor.tagName.toLowerCase() == WYMeditor.OL
              || ancestor.tagName.toLowerCase() == WYMeditor.UL)
                this._doc.execCommand(cmd,'',null);
        }

    break;

    case WYMeditor.INSERT_ORDEREDLIST: case WYMeditor.INSERT_UNORDEREDLIST:

        this._doc.execCommand(cmd,'',null);

        //Safari creates lists in e.g. paragraphs.
        //Find the container, and remove it.
        var focusNode = this.selected();
        var container = this.findUp(focusNode, WYMeditor.MAIN_CONTAINERS);
        if(container) jQuery(container).replaceWith(jQuery(container).html());

    break;
    
    default:

        if(param) this._doc.execCommand(cmd,'',param);
        else this._doc.execCommand(cmd,'',null);
    }
    
    //set to P if parent = BODY
    var container = this.selected();
    if(container && container.tagName.toLowerCase() == WYMeditor.BODY)
        this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);

    //add event handlers on doc elements
    this.listen();
};

/* @name selected
 * @description Returns the selected container
 */
WYMeditor.WymClassSafari.prototype.selected = function() {

    var sel = this._iframe.contentWindow.getSelection();
    var node = sel.focusNode;
    if(node) {
        if(node.nodeName == "#text") return(node.parentNode);
        else return(node);
    } else return(null);
};

WYMeditor.WymClassSafari.prototype.addCssRule = function(styles, oCss) {

    styles.insertRule(oCss.name + " {" + oCss.css + "}",
        styles.cssRules.length);
};


//keydown handler, mainly used for keyboard shortcuts
WYMeditor.WymClassSafari.prototype.keydown = function(evt) {
  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];
  
  // fix that shift+enter created new <p>
  if(evt.keyCode == 13 && evt.shiftKey)
    return false;
  
  if(evt.ctrlKey){
    if(evt.keyCode == 66){
      //CTRL+b => STRONG
      wym._exec(WYMeditor.BOLD);
      return false;
    }
    if(evt.keyCode == 73){
      //CTRL+i => EMPHASIS
      wym._exec(WYMeditor.ITALIC);
      return false;
    }
  }
};

//keyup handler, mainly used for cleanups
WYMeditor.WymClassSafari.prototype.keyup = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];
  
  wym._selected_image = null;
  var container = null;

  if(evt.keyCode == 13 && !evt.shiftKey) {
    //RETURN key
    //cleanup <br><br> between paragraphs
    jQuery(wym._doc.body).children(WYMeditor.BR).remove();
    
    //fix PRE bug #73
    container = wym.selected();
    if(container && container.tagName.toLowerCase() == WYMeditor.PRE)
        wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P); //create P after PRE
  }

  //fix #112
  if(evt.keyCode == 13 && evt.shiftKey) {
    wym._exec('InsertLineBreak');
  }
  
  if(evt.keyCode != 8
       && evt.keyCode != 17
       && evt.keyCode != 46
       && evt.keyCode != 224
       && !evt.metaKey
       && !evt.ctrlKey) {
      
    //NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
    //text nodes replaced by P
    
    container = wym.selected();
    var name = container.tagName.toLowerCase();

    //fix forbidden main containers
    if(
      name == "strong" ||
      name == "b" ||
      name == "em" ||
      name == "i" ||
      name == "sub" ||
      name == "sup" ||
      name == "a" ||
      name == "span" //fix #110

    ) name = container.parentNode.tagName.toLowerCase();

    if(name == WYMeditor.BODY || name == WYMeditor.DIV) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P); //fix #110 for DIV
  }
};

//TODO
WYMeditor.WymClassSafari.prototype.setFocusToNode = function(node) {
    /*var range = document.createRange();
    range.selectNode(node);
    var selected = this._iframe.contentWindow.getSelection();
    selected.addRange(range);
    selected.collapse(node, node.childNodes.length);
    this._iframe.contentWindow.focus();*/
};
/*
	Extend jQuery object to find editors by tag
*/

jQuery.extend({
  wymeditorByTag: function(jobj) {
	for (var i=0; i < WYMeditor.INSTANCES.length; i++) {
		if(WYMeditor.INSTANCES[i]._element.get(0) == jobj.get(0))
	    	return (WYMeditor.INSTANCES[i]);
	};
	return null;
  }
});



/*
	Constants: Extend global WYMeditor constants.
*/

jQuery.extend(WYMeditor, {
	TOGGLE: "{Wym_Toggle}"
})



/*
	Default settings for editor
*/

var RichtextConfig = {
//	html: '<p>Привет, МИР!<\/p>',
	lang: 'ru',
  skin: 'lam',
  state: 'editor',
  basePath: "/framework/plugins/b-editor/javascripts/",

	updateSelector: "#editor_submit",
	
	boxHtml: ""
		+ "<div class='lam-richtext lam-panel'>"
			+ "<div class='lr-tools lp-tools'>"
				+ WYMeditor.TOGGLE
				+ WYMeditor.TOOLS
			+ "</div>"
			+ "<div class='lr-main lp-main'>"
				+ WYMeditor.HTML
				+ WYMeditor.IFRAME
			+ "</div>"
		+ "</div>",
		
	mainBlockSelector: ".lr-main",

  toolsHtml: ""
		+ "<div class='wym_tools'>"
			+ "<ul>"
				+ WYMeditor.TOOLS_ITEMS
			+ "</ul>"
		+ "</div>",

	toolsSelectorLAM: ".lr-tools",
			
	toggleHtml: ""
		+ "<div class='lr-tools-toggle lr-tools-toggle-editor'>"
			+ "<span class='lrt-link lrt-link-editor hovered'>Editeur</span> | <span class='lrt-link lrt-link-html hovered'>HTML</span>"
		+ "</div>",
	
	toggleHtmlSelector: ".lr-tools-toggle",
	toggleHtmlClass: "lr-tools-toggle",
	toggleHtmlLinkSelector: ".lrt-link-",

  iframeHtml: ""
		+ "<div class='lr-main-iframe'>"
			+ "<iframe scrolling='" + (jQuery.browser.msie ? "yes" : "no") + "' "
				+ "src='"
				+ WYMeditor.IFRAME_BASE_PATH
				+ "wymiframe.html' "
				+ "onload='this.contentWindow.parent.WYMeditor.INSTANCES["
				+ WYMeditor.INDEX + "].initIframe(this)'"
			+ "></iframe>"
		+ "</div>",
		
	iframeBodySelector: ".lr-main-iframe",
	iframeSelector: ".lr-main-iframe iframe",

	htmlHtml: ""
		+ "<div class='lr-main-html'>"
			+ "<textarea class='lrm-html-val'></textarea>"
		+ "</div>",

	htmlSelector: ".lr-main-html",
	htmlValSelector: ".lrm-html-val",

  toolsItems: [
    { name: 'Bold', title: 'Strong', css: 'lr-tools-strong hovered clicked' }, 
    { name: 'Italic', title: 'Emphasis', css: 'lr-tools-emphasis hovered clicked' },
    { name: 'InsertOrderedList', title: 'Ordered_List', css: 'lr-tools-ordered-list hovered clicked' },
    { name: 'InsertUnorderedList', title: 'Unordered_List', css: 'lr-tools-unordered-list hovered clicked' },
    { name: 'CreateLink', title: 'Link', css: 'lr-tools-link hovered clicked' },
    { name : 'Unlink',  title: 'Unlink', css: 'lr-tools-unlink hovered clicked'},
    { name: 'Embed', title: 'Embed', css: 'lr-tools-embed hovered clicked' }
  ],
  
  toolsCreateLinkSelector: ".lr-tools-link",
  toolsEmbedSelector: ".lr-tools-embed",

  postInit: function(wym) {
		var $this = this;
		
		jQuery(".hovered").hover(function(){
			jQuery(this).addClass(this.className.match(/([^ ]+)/)[1] + "-hover");
		}, function(){
			jQuery(this).removeClass(this.className.match(/([^ ]+)/)[1] + "-hover");
		})

		jQuery(".clicked")
			.mousedown(function(){
				jQuery(this).addClass(this.className.match(/([^ ]+)/)[1] + "-down");
			})
			.mouseup(function(){
				jQuery(this).removeClass(this.className.match(/([^ ]+)/)[1] + "-down");
			})
		
		jQuery(document).mouseup(function(){
			jQuery(".clicked").each(function(){
				jQuery(this).removeClass(this.className.match(/([^ ]+)/)[1] + "-down");
			})
		})
		
		jQuery(wym._box).find(wym._options.htmlValSelector)
		  .unbind("keyup")
		  .tabby();

    jQuery(this._box).find(wym._options.toolSelector)
      .unbind("click")
      .click(function() {
        if(wym._options.state == "editor")
          wym.exec(jQuery(this).attr(WYMeditor.NAME));
        return(false);
      });


    if(bubble && bubble.onload){
      bubble.onload(function(){

        var bubble_link = bubble.append(""
    		  + "<div class='wym_" + WYMeditor.CREATE_LINK + "' style='display:none'>"
    		    + "<div class='wym-link-outer'>"
    		      + "<h3>Lien</h3>"
    		      + "<div class='item'><label>URL:</label><input type='text' /></div>"
    		      + "<button type='button' buttonType='simple'>Insérer</button>"
    		      + "<div class='clear'><div></div></div>"
    		    + "</div>"
    		  + "</div>",
  		    {
  		      oncreate: function(node){
  		        var _bubble = this;
  		        node.find("button").click(function(){
                var sStamp = wym.uniqueStamp();
                var input = node.find("input");
                var sUrl = input.val();
                if(sUrl.length > 0) {
                  
                  if (/^\s*www\./i.test(sUrl) && confirm('You are inserting link to the external resource. These links must begin with "http://".\n\nFix your link?'))
                		sUrl = 'http://' + sUrl;
                  
                  wym._exec(WYMeditor.CREATE_LINK, sStamp);
                  jQuery("a[href=" + sStamp + "]", wym._doc.body)
                      .attr(WYMeditor.HREF, sUrl)
                      .attr(WYMeditor.TITLE, jQuery(wym._options.titleSelector).val());
                }
                input.attr("value", "");
                _bubble.close({ node: node });
          		  return(false);
  		        })
  		        b_button_init();
      		  }
  		    }
      	)

        jQuery(wym._box).find(wym._options.toolSelector + "[name=CreateLink]")
          .unbind("click")
          .bind("click", function(event){
            if(wym._options.state == "editor")
    		      bubble.show(bubble_link, { event: event, from: this });
    		    return(false);
          })
        
        var bubble_embed = bubble.append(""
     		  + "<div class='wym_Embed' style='display:none'>"
     		    + "<div class='wym-embed-outer'>"
     		      + "<h3>Flash</h3>"
     		      + "<div class='item'><label>Objet:</label><textarea rows='6'></textarea></div>"
     		      + "<button type='button' buttonType='simple'>Insérer</button>"
     		      + "<div class='clear'><div></div></div>"
     		    + "</div>"
     		  + "</div>",
    	    {
    	      oncreate: function(node){
    	        var _bubble = this;
    	        node.find("button").click(function(){
                var sStamp = wym.uniqueStamp();
                var textarea = node.find("textarea");
                var object = textarea.val();
      				  var data = b_editor.embed.ObjectToData(object);
                if(object.length && data){
                  var url = "/images/d.gif?" + sStamp;
        				  wym._exec(WYMeditor.INSERT_IMAGE, url);

            		  jQuery("img", wym._doc.body).each(function(){
            		    if(jQuery(this).attr("src") == url)
            		      jQuery(this)
            				    .attr("type", "flash")
            				    .attr("width", data.box.width)
            				    .attr("height", data.box.height)
            		        .attr("src", url.replace(/\?(.*)/, ''))
            				    .attr("alt", b_editor.embed.print(data))
            				    .addClass("icon_video")
            		  });

                  wym._options.updateView(wym);
                }

                textarea.val("");
                _bubble.close({ node: node });
          		  return(false);
    	        })
    	        b_button_init();
      		  }
    	    }
      	)

        jQuery(wym._box).find(wym._options.toolSelector + "[name=Embed]")
          .unbind("click")
          .bind("click", function(event){
            if(wym._options.state == "editor")
  		        bubble.show(bubble_embed, { event: event, from: this });
    		    return(false);
          })

      })
    }


    //handle event on update element
    jQuery(wym._options.updateSelector)
      .parents("form")
      .submit(function(){
        wym.update("submit");
      })


		var iFrame = jQuery(wym._box).find(wym._options.iframeSelector);
		var iDoc = jQuery(iFrame.get(0).contentDocument);
		
		iDoc
		  .keyup(function(){
  			$this.updateView(wym)
  		})

		this.updateView(wym);
		
    wym.update("start");
		
		wym._iframe.contentWindow.focus()
		
	},
	
	updateView: function(wym){
		setTimeout(function(){
  		var h = jQuery(wym._doc.body).outerHeight();
  		if (h < 400) h = 400;

		  if(jQuery.browser.msie) h = 400;

  		var _iframe = jQuery(wym._iframe);
  		_iframe.parents(wym._options.mainBlockSelector).css({ height: h });
  		jQuery(wym._box).find(wym._options.htmlValSelector).css({ height: h });
		}, 1)

	}
};



/*
	Extend WYMeditor plugin
*/

WYMeditor.editor.prototype.toggleHtml = function(type) {
	// console.log(type);
	var wym = this;

	switch(type){
		case 'editor':
			jQuery(this._box)
				.find(this._options.htmlSelector)
				.hide();

			jQuery(this._box)
				.find(this._options.iframeBodySelector)
				.show();

			wym._options.updateView(wym);
			break;

		case 'html':
			jQuery(this._box)
				.find(this._options.htmlSelector)
				.show();
		
			jQuery(this._box)
				.find(this._options.iframeBodySelector)
				.hide();

			break;

	}
};

WYMeditor.editor.prototype.update = function(type, current){
	var wym = this;
	
	switch( type ){
		case 'start':
      // var html = HTMLtoXML( jQuery(this._element).val() );

      var html = LamEditor.Parser.parse( jQuery(this._element).val() );
		  html = this.updateTags( html, type );
      html = prepare( html );
		  
			wym._options.updateView(wym);

			jQuery(this._element).val(html).XMLformat();
		  this.html(html);
		  break;

		case 'editor':
		  if(current === true){
        // var html = HTMLtoXML(this.parser.parse( jQuery(this._doc.body).html() ));
        var html = LamEditor.Parser.parse( jQuery(this._doc.body).html() );
		  } else {
        // var html = HTMLtoXML(this.parser.parse( cleanup(jQuery(this._box).find(this._options.htmlValSelector).val()) ));
        var html = LamEditor.Parser.parse( jQuery(this._box).find(this._options.htmlValSelector).val() );
		  }
  	  html = this.updateTags( html, type );
      html = prepare( html );

			jQuery(this._element).val(html).XMLformat();
		  this.html(html);
			wym._options.updateView(wym);
			break;

		case 'html':
	    if( current === true ){
        // var html = HTMLtoXML(this.parser.parse( cleanup(jQuery(this._box).find(this._options.htmlValSelector).val()) ));
        var html = LamEditor.Parser.parse( jQuery(this._box).find(this._options.htmlValSelector).val() );
		  } else {
        // var html = HTMLtoXML(this.parser.parse( jQuery(this._doc.body).html() ));
        var html = LamEditor.Parser.parse( jQuery(this._doc.body).html() );
		  }
		  html = this.updateTags( html, type );
			jQuery(this._element).val(html);//.XMLformat();
			jQuery(this._box).find(this._options.htmlValSelector).val(html).XMLformat();
			break;

		case 'submit':
		  switch( this._options.state ){
		    case "editor":
          // var html = HTMLtoXML(this.parser.parse( jQuery(this._doc.body).html() ));
          var html = LamEditor.Parser.parse( jQuery(this._doc.body).html() );
		      break;
		    case "html":
          // var html = HTMLtoXML(this.parser.parse( cleanup(jQuery(this._box).find(this._options.htmlValSelector).val()) ));
          var html = LamEditor.Parser.parse( jQuery(this._box).find(this._options.htmlValSelector).val() );
		      break;
		  }
  	  html = this.updateTags( html, type );

		  jQuery(this._element).val(html).XMLformat();
		  break;

	}
	
	function cleanup( str ){
	  return str.replace(/<br ?\/?>/g, "<br>");
	}

  // fix problem with some browsers which not recognized <em> and <strong> tags in design mode
	function prepare( html ){
    return html
      .replace(/<em([^>]*)>/gi, "<i$1>")
      .replace(/<\/em>/gi, "</i>")
      .replace(/<strong([^>]*)>/gi, "<b$1>")
      .replace(/<\/strong>/gi, "</b>");
	}
	
};


WYMeditor.editor.prototype.updateTags = function(html, type){
	var $this = this;
//	var _html = jQuery("<div>" + html + "</div>");
	var _html = b_editor.regexp.cleanup(html);

	var pattern_object = /<(object)([^>]*)>(.*?)(<\/ ?\1>)/ig;
	var pattern_img = /<img([^>]*)\/?>/ig;
	
	if(this._options.parentObject){
		switch(type){
			case 'start':
        _html = OldFlashToImg(_html);
        _html = ObjectToImg(_html);
        break;

			case 'submit':

  		  switch(this._options.state){
  		    case "editor":
            _html = ImgToObject(_html);
            _html = ImgToName(_html);
            _html = NameToImg(_html);
	    
  		      break;
  		    case "html":
            _html = NameToImg(_html);
  		      break;
  		  }

        break;

			case 'editor':
        _html = NameToImg(_html);
        _html = ObjectToImg(_html);
				
				break;

			case 'html':
			  _html = ImgToObject(_html);
			  _html = ImgToName(_html);
				break;
		}
	};
	
	
  function OldFlashToImg(html){
    return html.replace(pattern_img, function(){
      var attrs = b_editor.regexp.getAttrs(arguments[1]);
      if(attrs["class"] && attrs["class"].indexOf("flash") != -1){
        return '<img class="icon_video" type="flash" src="/images/d.gif" width="' + attrs.width + '" height="' + attrs.height + '" alt="{ box: { width: ' + attrs.width + ', height: ' + attrs.height + ' }, params: { movie: \'' + attrs.alt + '\' }, url: \'' + attrs.alt + '\' }" />';
      } else {
        return arguments[0];
      }
    })
  };
	
	function ImgToObject(html){
    return html.replace(pattern_img, function(){
      var attrs = b_editor.regexp.getAttrs(arguments[1]);
      if(attrs.type == "flash"){
        var data = b_editor.embed.JSONtoData(attrs.alt);
        if(data){
          return b_editor.embed.DataToObject(data);
        }
      } else {
        return arguments[0];
      }
    })
	}

	function ObjectToImg(html){
    return html.replace(pattern_object, function(){
      var data = b_editor.embed.ObjectToData(arguments[0]);
      if(data) return '<img type="flash" width="' + data.box.width + '" height="' + data.box.height + '" src="/images/d.gif" alt="' + b_editor.embed.print(data) + '" class="icon_video" />';
    })
	}

	function ImgToName(html){
    return html.replace(pattern_img, function(){
      var attrs = b_editor.regexp.getAttrs(arguments[1]);
      if(attrs.src){
        var picture = $this._options.parentObject._config.pictures.getPictureByURL(attrs.src);
        if(picture && picture.is.init){
          var img =  '<img src="' + picture.o.name + '"';
          if(attrs.alt)
            img += ' alt="' + attrs.alt + '"';
          img += ' />';
          return img;
        }
      }
      return "";
    })
	}

	function NameToImg(html){
    return html.replace(pattern_img, function(){
      var attrs = b_editor.regexp.getAttrs(arguments[1]);
      if(attrs.src){
        var picture = $this._options.parentObject._config.pictures.getPictureByURL(attrs.src);
        if(picture && picture.is.init){
          //var img = '<img src="' + picture.o.article_url + '" width="' + picture.o.article_size.width + '" height="' + picture.o.article_size.height + '"';
	var img = '<img src="' + picture.o.article_url + '"';
          if(attrs.alt)
            img += ' alt="' + attrs.alt + '"';
          img += ' />';
          return img;
        }
      }
      return "";
    })
	}

//	return _html.html();
  return _html;
};


WYMeditor.editor.prototype.loadSkin = function() {

    if(WYMeditor.SKINS[this._options.skin] && WYMeditor.SKINS[this._options.skin].init)
       WYMeditor.SKINS[this._options.skin].init(this);

};

WYMeditor.editor.prototype.replaceStrings = function(sVal) {
  
  //replace all the strings in sVal and return it
  for (var key in WYMeditor.STRINGS[this._options.lang]) {
    sVal = WYMeditor.Helper.replaceAll(sVal, this._options.stringDelimiterLeft + key 
    + this._options.stringDelimiterRight,
    WYMeditor.STRINGS[this._options.lang][key]);
  };
  return(sVal);
};


WYMeditor.SKINS['lam'] = {

    init: function(wym) {

		var h = WYMeditor.Helper;
		var boxHtml = jQuery(wym._box).html();
		boxHtml = h.replaceAll(boxHtml, WYMeditor.TOGGLE, wym._options.toggleHtml);

		//l10n
		boxHtml = wym.replaceStrings(boxHtml);

		//load html in wymbox
		jQuery(wym._box).html(boxHtml);

		jQuery(wym._box).find(wym._options.toggleHtmlSelector + " span").click(function(){
		  
			jQuery(this).parents(wym._options.toggleHtmlSelector)
    		.removeClass(wym._options.toggleHtmlClass+'-editor')
    		.removeClass(wym._options.toggleHtmlClass+'-html');

			if(jQuery(this).is(wym._options.toggleHtmlLinkSelector + "editor")){
      	if(wym._options.state != "editor"){
      	  wym._options.state = "editor";
  				wym.update("editor");
  				wym.toggleHtml("editor");

    			jQuery(this).parents(wym._options.toggleHtmlSelector)
    				.addClass(wym._options.toggleHtmlClass+'-editor');

    			jQuery(this).parents(wym._options.toolsSelectorLAM)
    			  .find(wym._options.toolsSelector)
    			  .removeDependClass("disabled");

  			}
			}
			else if (jQuery(this).is(wym._options.toggleHtmlLinkSelector + "html")){
      	if(wym._options.state != "html"){
      	  wym._options.state = "html";
  				wym.update("html");
  				wym.toggleHtml("html")

    			jQuery(this).parents(wym._options.toggleHtmlSelector)
    				.addClass(wym._options.toggleHtmlClass+'-html');

    			jQuery(this).parents(wym._options.toolsSelectorLAM)
    			  .find(wym._options.toolsSelector)
    			  .addDependClass("disabled");
  			}
			}

			//partially fixes #121 when the user manually inserts an image
			if(!jQuery(wym._box).find(wym._options.htmlSelector).is(':visible'))
				wym.listen();

		})
	}
	
}

WYMeditor.STRINGS['RU'] = {
    Strong:           'Mise en évidence',
    Emphasis:         'Emphase',
    Superscript:      'Exposant',
    Subscript:        'Indice',
    Ordered_List:     'Liste Ordonnée',
    Unordered_List:   'Liste Non-Ordonnée',
    Indent:           'Imbriqué',
    Outdent:          'Non-imbriqué',
    Undo:             'Annuler',
    Redo:             'Rétablir',
    Link:             'Lien',
    Unlink:           'Supprimer le Lien',
    Image:            'Image',
    Table:            'Tableau',
    HTML:             'HTML',
    Paragraph:        'Paragraphe',
    Heading_1:        'Titre 1',
    Heading_2:        'Titre 2',
    Heading_3:        'Titre 3',
    Heading_4:        'Titre 4',
    Heading_5:        'Titre 5',
    Heading_6:        'Titre 6',
    Preformatted:     'Pré-formatté',
    Blockquote:       'Citation',
    Table_Header:     'Cellule de titre',
    URL:              'URL',
    Title:            'Titre',
    Alternative_Text: 'Texte alternatif',
    Caption:          'Légende',
    Summary:          'Résumé',
    Number_Of_Rows:   'Nombre de lignes',
    Number_Of_Cols:   'Nombre de colonnes',
    Submit:           'Envoyer',
    Cancel:           'Annuler',
    Choose:           'Choisir',
    Preview:          'Prévisualisation',
    Paste_From_Word:  'Copier depuis Word',
    Tools:            'Outils',
    Containers:       'Type de texte',
    Classes:          'Type de contenu',
    Status:           'Infos',
    Source_Code:      'Code source'
};



/*
 * LookAtMe Editor
 * created by Egor Hmelyoff (hmelyoff@gmail.com)
 *
 */

/* define global object */
var LamEditor, LamEditorConfig;

(function($) {

	function debug(str) {
		if (window.console && window.console.log)
		window.console.log("[Editor: '" + str + "']");
	};
	
	function replaceAll(str, old, rep){
        var rExp = new RegExp(old, "g");
        return(str.replace(rExp, rep));
	}

	/* define local config */
	LamEditorConfig = {};
	$.extend(LamEditorConfig, {

		swfu: {
			upload_url: "/upload/swf/session_id/" + encodeURIComponent($.cookie(sess_name)), 
			flash_url: "/flash/swfupload.swf",
			file_types: "*.jpe; *.jpg; *.jpeg; *.tiff; *.tif; *.png; *.bmp"
		},
		
		removeURL: '/article_images/{PictureID}',
		removeParams: {
			"_method": "delete"
		},

		richtextSelector: "div.le-richtext textarea.lam-richtext",
		richtextConfig: RichtextConfig,

		richtextToolbar: "div.le-richtext div.lp-tools",
		richtextContent: "div.le-richtext div.lp-main",
		
		picturesNode: ".le-pictures",
		picturesRoot: ".lam-pictures",
		picturesPanel: ".le-pictures .lam-pictures",
		picturesMainNode: ".lp-main .lp-main-in",

		picturesToolsSelector: ".lpic-tools-",
		picturesToolsDisabledClass: "lpic-tools-disabled",

		picturesItemSelector: ".lp-main .lp-main-in img",

		picturesLoadHtml: ""
			+ "<div class='lp-load-link'>"
				+ "<span class='lp-load-link-empty'>Uploader des images</span>"
				+ "<span>Uploader des images</span>"
				+ "<div id='LamEditorLoadObject'></div>"
			+ "</div>",
		picturesLoadId: "LamEditorLoadObject",
		picturesLoadSelector: ".lp-load-link",
		pictureNS: "picture_",
		

		RESOURCE       : "{Resource}",
		PICTUREID      : "{PictureID}",
		PICTUREUID     : "{PictureUID}",
		PICTURENAME    : "{PictureName}",
		PICTUREPREVIEW : "{PicturePreview}",

		pictureHtml: ''
			+ '<div class="lp-picture">'
				+ '<div class="lp-picture-bg"></div>'
				+ '<ul>'
					+ '<li class="lp-picture-title"><input id="{PictureID}" class="checkbox" name="{PictureID}" type="checkbox" /><label for="{PictureID}">{PictureName}</label></li>'
					+ '<li class="lp-picture-preview">'
						+ '<table>'
							+ '<tr>'
								+ '<td>'
									+ '{PicturePreview}'
								+ '</td>'
							+ '</tr>'
						+ '</table>'
					+ '</li>'
					+ '<li class="lp-picture-link"><span>insérer dans le texte</span></li>'
				+ '</ul>'
				+ '<input type="hidden" name="{Resource}[image_ids][]" value="{PictureUID}" />'
			+ '</div>',
		pictureClass: 'lp-picture',
		pictureClassSelectedAdd: '-selected',
		pictureClassLoadingAdd: '-loading',
		pictureClassRemovingAdd: '-removing',
		pictureInsertSelector: '.lp-picture-link span'
		
	})

	$(document).ready(function() {
	//	var e = jQuery('.lam-richtext');
	//	console.dir(jQuery.wymeditorByTag(e));
		
		/* init editor */
		$(".lam-editor").each(function(){
			new LamEditor(this, LamEditorConfig);
		})
	
	});

	/*
		Main editor object
	*/
	this.LamEditor = function(){ this.init.apply(this, arguments) }
	LamEditor.prototype = {
		preInit: function(){},
		postInit: function(){},
		
		init: function(){
			this._config = arguments[1] ? arguments[1]: {};
			$.extend(this._config, {
				root: $(arguments[0])
			})

			this.preInit();
			this.initRichtext();
			if(this.initPictures()){
				this.bindEvents();
				this.postInit();
			}
			
		},
		
		initRichtext: function(){
			try{
				this._config.richtextNode = this._config.root.find(this._config.richtextSelector).wymeditor($.extend(this._config.richtextConfig, { parentObject: this }));
				this._config.richtext = $.wymeditorByTag(this._config.richtextNode);
				this._config.richtextResource = this._config.richtextNode.attr("resource");
			}
			catch(e){
				debug("wymeditor not defined: " + e.message);
				return false;
			}
		},
		
		initPictures: function(){
			this._config.pictures = new LamEditor.Pictures(this._config.picturesNode, this);
			if(!this._config.pictures.o.init)
				return false;
			else {
				return true;
			}
		},
		
		bindEvents: function(){
		  var wait = false;
		  var offset = 33;

      var outer = $("<div>").addClass("lam-richtext lam-editor lam-panel lam-fixed").appendTo(document.body);

      var toolbarNode = this._config.root.find(this._config.richtextToolbar);
      var toolbarDummy = createDummy(toolbarNode);

      var picturesNode = this._config.root.find(this._config.picturesPanel);
      var picturesDummy = createDummy(picturesNode);

      var contentNode = this._config.root.find(this._config.richtextContent);

      $(window).scroll(function(){
        var t = $(window).scrollTop();
        var _offset = offset;
        if(!$(document.body).is(".b-user-panel-fixed")) _offset = 0;

        var contentSizes = {
          top: contentNode.offset().top,
          height: contentNode.height()
        }

        var _dummy = {
          offset: toolbarDummy.offset(),
          width: toolbarDummy.width(),
          height: toolbarDummy.height()
        }

        if(picturesDummy)
          var _dummyPictures = {
            offset: picturesDummy.offset(),
            width: picturesDummy.width(),
            height: picturesDummy.height()
          } 
        
        if(t > _dummy.offset.top-_offset && (contentSizes.top+contentSizes.height)-(t+_dummy.height) > 400+_offset){
          if(!wait){
            wait = true;

            showDummy(toolbarDummy);
            toolbarNode.appendTo(outer);
            toolbarNode.css({ position: "absolute", left: _dummy.offset.left, top: 0, zIndex: 2, width: _dummy.width });

            if(picturesDummy){
              picturesNode.appendTo(outer);
              picturesNode.css({ position: "absolute", left: _dummyPictures.offset.left, top: 0, zIndex: 2, width: _dummyPictures.width });
            }
          }

        } else if (t > _dummy.offset.top-_offset && (contentSizes.top+contentSizes.height)-(t+_dummy.height) <= 400+_offset) {
          if(wait){
            wait = false;

            toolbarNode.removeAttr("style").insertBefore(toolbarDummy);
            toolbarNode.css({ position: "absolute", left: 0, top: (contentSizes.height)-400 , zIndex: 2, width: _dummy.width })

            if(picturesDummy){
              picturesNode.removeAttr("style").insertBefore(picturesDummy);
              picturesNode.css({ position: "absolute", left: 0, top: (contentSizes.height)-400 , zIndex: 2, width: _dummyPictures.width })
            }
          }
        } else {
          if(wait){
            wait = false;

            toolbarNode.removeAttr("style").insertBefore(toolbarDummy);
            showDummy(toolbarDummy, false);

            if(picturesDummy)
              picturesNode.removeAttr("style").insertBefore(picturesDummy);
          }
        }
      })
      
      function createDummy(node){
        if(node.is(":visible")){
          var dummy = node.clone();
          dummy.empty().css({ position: "absolute", left: 0, top: 0, visibility: "hidden", zIndex: -1, width: node.width(), height: node.height() });
          node.after(dummy);
          return dummy;
        } else return false;
      }
      function showDummy(dummy, b){
        if(b === false){
          dummy.css({ position: "absolute", zIndex: -1, visibility: "hidden" });
        } else {
          dummy.css({ position: "static", zIndex: 1, visibility: "visible" });
        }
      }
      
		}
	}



	/*
		Object to work with pictures
	*/
	LamEditor.Pictures = function(){ this.init.apply(this, arguments); }
	LamEditor.Pictures.prototype = {
		init: function(){
			try{
				$.extend(this.o = {
					parent: arguments[1]
				}, {
					init: true,
					ptr: this.o.parent._config.root.find(arguments[0]),
					tools: {
						checkall: false,
						insert: false,
						remove: false
					},
					pictures: new Array(),
					trash: new Array()
				})
				this._config = this.o.parent._config;

				this.o.inner = this.o.ptr.find(this._config.picturesMainNode);
				this.o.root = this.o.ptr.find(this._config.picturesRoot);
				
			}
			catch(e){
				debug(["pictures could not defined", e]);
				return this.o.init = false;
			}
			
			this.initLoaded();
			this.toolsController();
			this.bindEvents();
		},
		
		initLoaded: function(){
			var $this = this;
			this.o.ptr.find(this._config.picturesItemSelector).each(function(){
				// init LamEditor.Pictures.Picture object
				$this.o.pictures.push(new LamEditor.Pictures.Picture(this, $this));
			})
		},
		
		loadLink: function(){
			if(!this.o.loadLink){
				this.o.loadLink = this.o.ptr.find(this._config.picturesRoot).append(this._config.picturesLoadHtml).find(this._config.picturesLoadSelector);
				this.build_uploader();
				
			}

			if(!this.o.pictures.length)
				this.o.loadLink.addClass(this.o.loadLink.attr("class").match(/([^ ]+)/)[1] + "-empty")
			else
				this.o.loadLink.removeClass(this.o.loadLink.attr("class").match(/([^ ]+)/)[1] + "-empty")
				
		},
		
		build_uploader: function() {
			var $this = this;

			var handlers = {
				file_queued_function: function(object){
					$this.o.pictures.push(new LamEditor.Pictures.Picture(object, $this));
					$this.loadLink();
				},

				file_dialog_complete_function: function(selected, queued){
					if(queued > 0)
						this.startUpload();
				},
				
				upload_start_function: function(object){
					//debug("upload_start_function");
					//console.log(arguments);
				},
				
				upload_error_function: function(object, code, message){
					//debug("upload_error_function")
					//console.log(arguments);
					var picture = $this.getPictureById(object);
					$this.removeImage(picture);
				},
				
				upload_success_function: function(object, data){
					var picture = $this.getPictureById(object);
					if(picture)
						picture.initByJSON(data);
					
					$this.toolsController();
				},
				
				upload_complete_function: function(object){
					this.startUpload();
				}
			}

			var swfu_settings = {
				begin_upload_on_queue: true,
				use_server_data_event: true,

				upload_url: this._config.swfu.upload_url,
				flash_url: this._config.swfu.flash_url,
				file_types : this._config.swfu.file_types,
				file_post_name : "files[swfupload]",

				file_dialog_complete_handler : handlers.file_dialog_complete_function,
				file_queued_handler : handlers.file_queued_function,
				upload_start_handler : handlers.upload_start_function,
				upload_progress_handler : handlers.upload_progress_function,
				upload_error_handler : handlers.upload_error_function,
				upload_success_handler : handlers.upload_success_function,
				upload_complete_handler : handlers.upload_complete_function,

				button_width: "100%",
				button_height: "100%",
				button_left: 0,
				button_placeholder_id: this._config.picturesLoadId,
				button_window_mode: "transparent",
				button_cursor : SWFUpload.CURSOR.HAND
			};

			this.swfu = new SWFUpload(swfu_settings);
		},
		
		each: function(callback){
			for (var i=0; i < this.o.pictures.length; i++) {
				callback.call(this.o.pictures[i]);
			};
		},
		
		getPictureById: function(param){
			var _id = (typeof param == 'object') ? param.id : param;
			
			for (var i=0; i < this.o.pictures.length; i++) {
				if(this.o.pictures[i].o.id == _id)
					return this.o.pictures[i];
			};
			return false;
		},

		getPictureByURL: function(url){
			for (var i=0; i < this.o.pictures.length; i++) {
				if(url.indexOf(this.o.pictures[i].o.name) != -1 || url.indexOf(this.o.pictures[i].o.article_url) != -1 || this.o.pictures[i].o.article_url.indexOf(url) != -1)
					return this.o.pictures[i];
			};
			return false;
		},

    getIdFromUrl: function(url){
      var matches =  url.match(/.*article_image-image\/\w{2}\/\w{2}\/(\d+)\/.*/i);
      return matches ? matches[1] : null;
    },

		getSelected: function(){
			var arr = new Array();

			for (var i=0; i < this.o.pictures.length; i++) {
				if(this.o.pictures[i].is.selected)
					arr.push(this.o.pictures[i]);
			};
			return arr;
		},
		
		bindEvents: function(){
			var $this = this;
			this.loadLink();
			this.o.ptr
				.find(this._config.picturesToolsSelector + "checkall")
  				.change(function(){
  					var checked = this.checked;
  					$this.each(function(){
  						this.select(checked)
  					})
  					$this.toolsController();
  				})
  				.focus(function(){
  				  $(this).change();
  				})
  				.click(function(){
  				  $(this).change();
  				})
  			.end()
				.find(this._config.picturesToolsSelector + "insert").click(function(){
					var selected = $this.getSelected();
					for (var i=0; i < selected.length; i++) {
						$this.insertImage(selected[i]);
					};
					return(false);
				}).end()
				.find(this._config.picturesToolsSelector + "remove").click(function(){
					var selected = $this.getSelected();
					if(confirm("Etes-vous sûr de supprimer ces images?")){
						for (var i=0; i < selected.length; i++) {
							$this.removeImage(selected[i]);
						};
					}
				});
		},
		
		insertImage: function(obj){
			var wym = this._config.richtext;
			
			if(wym._options.state == "editor"){
  			var sStamp = wym.uniqueStamp();
  			var url = obj.o.article_url + "?" + sStamp;
  			wym._exec(WYMeditor.INSERT_IMAGE, url);

  		  jQuery("img", wym._doc.body).each(function(){
  		    if(jQuery(this).attr("src") == url)
  		      jQuery(this)
  		        .attr("src", url.replace(/\?(.*)/, ''))
              .attr("width", obj.o.article_size.width)
              .attr("height", obj.o.article_size.height)
  		  });

	      wym._options.updateView(wym)
      }
			
		},
		
		removeImage: function(obj){
			var $this = this;
			obj.status("removing");
			obj.is.removed = true;
			$this.cleanup();
			obj.o.ptr.animate({ opacity: 0 }, 500, function(){
				$(this).remove();
				$this.loadLink();
			})
		},
		
		cleanup: function(){
			var wym = this._config.richtext;

			for (var i=this.o.pictures.length-1; i >= 0; i--) {
				if(this.o.pictures[i].is.removed){
					var pic = this.o.pictures.splice(i, 1)[0];
					this.o.trash.push(pic);

					var h = WYMeditor.Helper;
					var url = this._config.removeURL;
					url = h.replaceAll(url, this._config.PICTUREID, pic.o.id);
					$.post(url, this._config.removeParams, function(data, textStatus){
						debug("success removed -> " + data);
					})
				}
			};
			this.toolsController();
			wym.update(wym._options.viewState, true);
		},
		
		toolsController: function(){
			var tools = {
				checkall: false,
				insert: false,
				remove: false
			}
			if(this.o.pictures.length)
				tools.checkall = true
				
			if(this.getSelected().length)
				$.extend(tools, {
					insert: true,
					remove: true
				});
				
			var _checkall = this.o.root.find(this._config.picturesToolsSelector + "checkall");
			
			if(this.getSelected().length == this.o.pictures.length && this.o.pictures.length != 0)
				_checkall.attr("checked", "checked")
			else
				_checkall.removeAttr("checked")
				
			this.tools(tools);
		},
		
		tools: function(o){
			var $this = this;
			switch(typeof o){
				case 'object':
					for(key in o){
						set(key, o[key]);
					}
					break;
				case 'boolean':
					for(key in this.o.tools){
						set(key, o);
					}
					break;
				default:
					for(key in this.o.tools){
						set(key, this.o.tools[key]);
					}
					break;
			}
			
			function set(param, value){
				var _o = $this.o.root.find($this._config.picturesToolsSelector + param);
				if(_o.get(0).tagName == "INPUT"){
					if(value){
						_o.removeAttr("disabled");
						_o.parent().removeClass($this._config.picturesToolsDisabledClass);
					} else {
						_o.attr("disabled", "disabled");
						_o.parent().addClass($this._config.picturesToolsDisabledClass);
					}
				} else {
					if(value)
						_o.removeClass($this._config.picturesToolsDisabledClass);
					else
						_o.addClass($this._config.picturesToolsDisabledClass);
				}
			}
		}
	}



	/*
		Picture item object
	*/
	LamEditor.Pictures.Picture = function(){ this.init.apply(this, arguments); }
	LamEditor.Pictures.Picture.prototype = {
		init: function(){
			// default variables
			try{
				$.extend(this.o = { parent: arguments[1] ? arguments[1] : null }, {
				
				});
				this._config = this.o.parent._config;

				this.is = {
					init: false,
					removed: false,
					selected: false
				}
			}
			catch(e){
				debug(["pictures could not defined", e]);
				return this.is.init = false;
			}
			
			switch(typeof arguments[0]){
				case 'object':
					if(arguments[0].nodeType && arguments[0].nodeType == 1){
						this.initByNode(arguments[0]);
					} else {
						this.initBySWFUpload(arguments[0]);
					}
					break;
				default:
					debug("unknow param type for init LamEditor.Pictures.Picture item");
					break;
			}
		},
		
		initBySWFUpload: function(object){
			var html = this._config.pictureHtml;
			
			html = replaceAll(html, this._config.PICTUREID, object.id);
			html = replaceAll(html, this._config.PICTURENAME, this._config.pictureNS);

			$.extend(this.o, {
				ptr: $(html),
				id: object.id,
				name: object.name
			})
			
			this.o.parent.o.inner.append(this.o.ptr);
			this.status('loading');
		},
		
		initByJSON: function(json){
			var data = eval('(' + json + ')');

			$.extend(this.o, data);
			this.o.name = this._config.pictureNS + this.o.id;
			
			var html = this.o.ptr.html();
			html = replaceAll(html, this._config.pictureNS, this.o.name);
			html = replaceAll(html, this._config.PICTUREUID, this.o.id);
			this.o.ptr.html(html);
			
			this._init();
		},
		
		initByNode: function(node){
			node = $(node);
			var html = this._config.pictureHtml;
			var data = eval('(' + node.attr("alt") + ')');
			
			$.extend(this.o, data);
			this.o.name = this._config.pictureNS + this.o.id;

			html = replaceAll(html, this._config.PICTUREID, this.o.id);
			html = replaceAll(html, this._config.PICTUREUID, this.o.id);
			html = replaceAll(html, this._config.PICTURENAME, this.o.name);

			this.o.ptr = $(html);
			node.replaceWith(this.o.ptr);
			
			this._init();
		},
		
		_init: function(){
			var html = this.o.ptr.html();

			var img = '<img src="' + this.o.article_url + '"';
			if(this.o.article_size.width > this.o.article_size.height)
			  img += ' width="140"';
			else
			  img += ' height="140"';

			img += ' alt="' + this.o.name + '" />';

			html = replaceAll(html, this._config.PICTUREPREVIEW, img);
			html = replaceAll(html, this._config.RESOURCE, this._config.richtextResource);
			
			this.o.ptr.empty().append(html);
			this.status();
			this.bindEvents();
			this.is.init = true;
		},
		
		bindEvents: function(){
			var $this = this;
			this.o.ptr
				.find("input[type=checkbox]")
  				.change(function(){
  					$this.select(this.checked);
  					$this.o.parent.toolsController();
  				})
  				.focus(function(){
  				  $(this).change();
  				})
  				.click(function(){
  				  $(this).change();
  				})
  			.end()
  			.mouseup(function(){
  			  //$this.o.ptr.find("input[type=checkbox]").blur();
  			})
				.find(this._config.pictureInsertSelector)
				  .click(function(){
  					$this.o.parent.insertImage($this);
  				})
		},
		
		select: function(b){
			if(this.is.init)
				if(b){
					this.status("selected")
					this.is.selected = true;
					this.o.ptr.find("input[type=checkbox]").attr("checked", "checked")
				} else {
					this.status()
					this.is.selected = false;
					this.o.ptr.find("input[type=checkbox]").removeAttr("checked")
				}
		},
		
		status: function(s){
			switch(s){
				case 'loading':
					this.o.ptr.addClass(this._config.pictureClass + this._config.pictureClassLoadingAdd);
					this.o.ptr.find("input[type=checkbox]").attr("disabled", "disabled")
					break;
					
				case 'selected':
					this.o.ptr.addClass(this._config.pictureClass + this._config.pictureClassSelectedAdd);
					break;
					
				case 'removing':
					this.o.ptr.addClass(this._config.pictureClass + this._config.pictureClassRemovingAdd);
					break;

				default:
					// remove loading state
					this.o.ptr.removeClass(this._config.pictureClass + this._config.pictureClassLoadingAdd);
					this.o.ptr.find("input[type=checkbox]").removeAttr("disabled")

					// remove selected state
					this.o.ptr.removeClass(this._config.pictureClass + this._config.pictureClassSelectedAdd);

					// remove removind state
					// this.o.ptr.removeClass(this._config.pictureClass + this._config.pictureClassRemovingAdd);
			}
		}
	}
	

})(jQuery); 
/*
 * HTML Parser By John Resig (ejohn.org)
 * Original code by Erik Arvidsson, Mozilla Public License
 * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
 *
 * // Use like so:
 * HTMLParser(htmlString, {
 *     start: function(tag, attrs, unary) {},
 *     end: function(tag) {},
 *     chars: function(text) {},
 *     comment: function(text) {}
 * });
 *
 * // or to get an XML string:
 * HTMLtoXML(htmlString);
 *
 * // or to get an XML DOM Document
 * HTMLtoDOM(htmlString);
 *
 * // or to inject into an existing document/DOM node
 * HTMLtoDOM(htmlString, document);
 * HTMLtoDOM(htmlString, document.body);
 *
 */

(function(){

	// Regular Expressions for parsing tags and attributes
	var startTag = /^<(\w+)((?:\s+[\w\:]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,
		endTag = /^<\/(\w+)[^>]*>/,
		attr = /([\w:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g;
		
	// Empty Elements - HTML 4.01
	var empty = makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed");

	// Block Elements - HTML 4.01
	var block = makeMap("address,applet,blockquote,button,center,dd,del,dir,div,dl,dt,fieldset,form,frameset,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");

	// Inline Elements - HTML 4.01
	var inline = makeMap("a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");

	// Elements that you can, intentionally, leave open
	// (and which close themselves)
	var closeSelf = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");

	// Attributes that have their values filled in disabled="disabled"
	var fillAttrs = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");

	// Special Elements (can contain anything)
	var special = makeMap("script,style");

	var HTMLParser = this.HTMLParser = function( html, handler ) {
		var index, chars, match, stack = [], last = html;
		stack.last = function(){
			return this[ this.length - 1 ];
		};

		while ( html ) {
			chars = true;

			// Make sure we're not in a script or style element
			if ( !stack.last() || !special[ stack.last() ] ) {

				// Comment
				if ( html.indexOf("<!--") == 0 ) {
					index = html.indexOf("-->");
	
					if ( index >= 0 ) {
						if ( handler.comment )
							handler.comment( html.substring( 4, index ) );
						html = html.substring( index + 3 );
						chars = false;
					}
	
				// end tag
				} else if ( html.indexOf("</") == 0 ) {
					match = html.match( endTag );
	
					if ( match ) {
						html = html.substring( match[0].length );
						match[0].replace( endTag, parseEndTag );
						chars = false;
					}
	
				// start tag
				} else if ( html.indexOf("<") == 0 ) {
					match = html.match( startTag );
	
					if ( match ) {
						html = html.substring( match[0].length );
						match[0].replace( startTag, parseStartTag );
						chars = false;
					}
				}

				if ( chars ) {
					index = html.indexOf("<");
					
					var text = index < 0 ? html : html.substring( 0, index );
					html = index < 0 ? "" : html.substring( index );
					
					if ( handler.chars )
						handler.chars( text );
				}

			} else {
				html = html.replace(new RegExp("(.*)<\/" + stack.last() + "[^>]*>"), function(all, text){
					text = text.replace(/<!--(.*?)-->/g, "$1")
						.replace(/<!\[CDATA\[(.*?)]]>/g, "$1");

					if ( handler.chars )
						handler.chars( text );

					return "";
				});

				parseEndTag( "", stack.last() );
			}

			if ( html == last )
				throw "Parse Error: " + html;
			last = html;
		}
		
		// Clean up any remaining tags
		parseEndTag();

		function parseStartTag( tag, tagName, rest, unary ) {
		  if( tagName ) tagName = tagName.toLowerCase();

			if ( block[ tagName ] ) {
				while ( stack.last() && inline[ stack.last() ] ) {
					parseEndTag( "", stack.last() );
				}
			}

			if ( closeSelf[ tagName ] && stack.last() == tagName ) {
				parseEndTag( "", tagName );
			}

			unary = empty[ tagName ] || !!unary;

			if ( !unary )
				stack.push( tagName );
			
			if ( handler.start ) {
				var attrs = [];
	
				rest.replace(attr, function(match, name) {
					var value = arguments[2] ? arguments[2] :
						arguments[3] ? arguments[3] :
						arguments[4] ? arguments[4] :
						fillAttrs[name] ? name : "";
					
					attrs.push({
						name: name,
						value: value,
						escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') //"
					});
				});
	
				if ( handler.start )
					handler.start( tagName, attrs, unary );
			}
		}

		function parseEndTag( tag, tagName ) {
		  if( tagName ) tagName = tagName.toLowerCase();

			// If no tag name is provided, clean shop
			if ( !tagName )
				var pos = 0;
				
			// Find the closest opened tag of the same type
			else
				for ( var pos = stack.length - 1; pos >= 0; pos-- )
					if ( stack[ pos ] == tagName )
						break;
			
			if ( pos >= 0 ) {
				// Close all the open elements, up the stack
				for ( var i = stack.length - 1; i >= pos; i-- )
					if ( handler.end )
						handler.end( stack[ i ] );
				
				// Remove the open elements from the stack
				stack.length = pos;
			}
		}
	};
	
	this.HTMLtoXML = function( html ) {
		var results = "";
		
		HTMLParser(html, {
			start: function( tag, attrs, unary ) {
				results += "<" + tag;
		
				for ( var i = 0; i < attrs.length; i++ )
					results += " " + attrs[i].name + '="' + attrs[i].escaped + '"';
		
				results += (unary ? "/" : "") + ">";
			},
			end: function( tag ) {
				results += "</" + tag + ">";
			},
			chars: function( text ) {
				results += text;
			},
			comment: function( text ) {
				results += "<!--" + text + "-->";
			}
		});
		
		return results;
	};
	
	this.HTMLtoDOM = function( html, doc ) {
		// There can be only one of these elements
		var one = makeMap("html,head,body,title");
		
		// Enforce a structure for the document
		var structure = {
			link: "head",
			base: "head"
		};
	
		if ( !doc ) {
			if ( typeof DOMDocument != "undefined" )
				doc = new DOMDocument();
			else if ( typeof document != "undefined" && document.implementation && document.implementation.createDocument )
				doc = document.implementation.createDocument("", "", null);
			else if ( typeof ActiveX != "undefined" )
				doc = new ActiveXObject("Msxml.DOMDocument");
			
		} else
			doc = doc.ownerDocument ||
				doc.getOwnerDocument && doc.getOwnerDocument() ||
				doc;
		
		var elems = [],
			documentElement = doc.documentElement ||
				doc.getDocumentElement && doc.getDocumentElement();
				
		// If we're dealing with an empty document then we
		// need to pre-populate it with the HTML document structure
		if ( !documentElement && doc.createElement ) (function(){
			var html = doc.createElement("html");
			var head = doc.createElement("head");
			head.appendChild( doc.createElement("title") );
			html.appendChild( head );
			html.appendChild( doc.createElement("body") );
			doc.appendChild( html );
		})();
		
		// Find all the unique elements
		if ( doc.getElementsByTagName )
			for ( var i in one )
				one[ i ] = doc.getElementsByTagName( i )[0];
		
		// If we're working with a document, inject contents into
		// the body element
		var curParentNode = one.body;
		
		HTMLParser( html, {
			start: function( tagName, attrs, unary ) {
				// If it's a pre-built element, then we can ignore
				// its construction
				if ( one[ tagName ] ) {
					curParentNode = one[ tagName ];
					return;
				}
			
				var elem = doc.createElement( tagName );
				
				for ( var attr in attrs )
					elem.setAttribute( attrs[ attr ].name, attrs[ attr ].value );
				
				if ( structure[ tagName ] && typeof one[ structure[ tagName ] ] != "boolean" )
					one[ structure[ tagName ] ].appendChild( elem );
				
				else if ( curParentNode && curParentNode.appendChild )
					curParentNode.appendChild( elem );
					
				if ( !unary ) {
					elems.push( elem );
					curParentNode = elem;
				}
			},
			end: function( tag ) {
				elems.length -= 1;
				
				// Init the new parentNode
				curParentNode = elems[ elems.length - 1 ];
			},
			chars: function( text ) {
				curParentNode.appendChild( doc.createTextNode( text ) );
			},
			comment: function( text ) {
				// create comment node
			}
		});
		
		return doc;
	};

	function makeMap(str){
		var obj = {}, items = str.split(",");
		for ( var i = 0; i < items.length; i++ )
			obj[ items[i] ] = true;
		return obj;
	}
})();


(function( $ ) {

  LamEditor.Parser = {

    _tags: ["a", "img", "p", "strong", "b", "em", "i", "del", "br", "hr", "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6", "object", "param", "table", "tbody", "tr", "td", "th"],
    _attrs: ["href", "alt", "src", "width", "height", "border", "tag", "name", "value", "type", "class", "colspan", "rowspan"],
    
    _replace: { "b": "strong", "i": "em" },
    _regexp: { "strong": /bold/, "em": /italic/ },

    parse: function( htmlString ){
      var results = "";
      var _tags = new Array();
      var _format = new Array();


      htmlString = b_editor.regexp.cleanup( htmlString );

      HTMLParser(htmlString, {
        start: function( tag, attrs, unary ){
          //console.log(attrs);
          tag = tag.toLowerCase(); // ie fix
          
          if(!_tags[tag]) _tags[tag] = 0; _tags[tag]++; // calculate opened tags
          
          if( LamEditor.Parser.isAllow(tag, "tags") ){
            tag = LamEditor.Parser.replaceTag( tag );
            results += "<" + tag;

            for ( var i = 0; i < attrs.length; i++ ){
              if( LamEditor.Parser.isAllow(attrs[i].name, "attrs") ){
                results += " " + attrs[i].name + '="' + attrs[i].escaped + '"';
              }
            }

            results += (unary ? "/" : "") + ">";

          } else {
            var formatted = LamEditor.Parser.getFormatTag( tag, attrs );
            if( formatted ){
              results += "<" + formatted + ">";
              _format.push({ tag: tag, level: _tags[tag], format: formatted });
            }
            
          }
        },
        end: function( tag ){
          tag = tag.toLowerCase(); // ie fix

          if( LamEditor.Parser.isAllow(tag, "tags") ){
            tag = LamEditor.Parser.replaceTag(tag);
            results += "</" + tag + ">";

          } else {
            for (var i=_format.length-1; i >= 0; i--) {
              if( _format[i].tag == tag && _format[i].level == _tags[tag] ){
                results += "</" + _format[i].format + ">";
                _format.splice(i, 1);
                break;
              }
            };
          }

          _tags[tag]--; // close tag
        },
        chars: function( text ){
          results += text;
        },
        comment: function( text ){} // remove any comments
      });
      
      // alert(results);
      
      return results;
    },
    
    isAllow: function( tag, type ){
      if( $.inArray(tag, this["_" + type]) != -1 )
        return true;

      return false;
    },
    
    replaceTag: function( tag ){
      for( bad in this._replace ){
        if ( bad == tag ) return this._replace[bad];
      }
      return tag;
    },
    
    getFormatTag: function( tag, attrs ){
      var self = this;

      if( tag == "span" && attrs ){
        for ( var i = 0; i < attrs.length; i++ ){
          if( attrs[i].name == "style" ){
            var tag = _get(attrs[i].value);
            if( tag ) return tag;
          }
        }
      }
      
      function _get( style ){
        for( tag in self._regexp ){
          if(self._regexp[tag].test( style )) return tag;
        }
        
        // if(/bold/.test( style )) return 'strong';
        // if(/italic/.test( style )) return 'em';

        return false;
      }
      
      return false;
    }
  }

})(jQuery);

(function($) {

  if(!this.b_editor)
    this.b_editor = {};
  
  this.b_editor.regexp = {

    cleanup: function(text){

			function process(items) {
				$.each(items, function(v) {
					// Remove or replace
					if (this.constructor == RegExp)
						text = text.replace(this, '');
					else
						text = text.replace(this[0], this[1]);
				});
			};

    	process([
    	  [/[\n\t\0\v\f\r]/g, " "], // remove all string modifiers
    	  [/ {2,}/g, " "],          // remove double[or more] spaces
    	])
    	

    	// remove spaces between block tags
    	var blocks = "div|p|hr|ul|ol|li|h1|h2|h3|h4|h5|h6|object|param|table|tbody|tr|td|th";
    	var rBlocks = new RegExp("<(\/?)(" + blocks + "){1}([^>]*)> +<(\/?)(" + blocks + "){1}([^>]*)>", "gi");
    	while( rBlocks.test(text) ){
    	  text = text.replace(rBlocks, "<$1$2$3><$4$5$6>");
    	}


    	// Detect Word content and process it more agressive
    	if (/(class=\"?Mso|style=\"[^\"]*\bmso\-|w:WordDocument)/.test(text)) {

				process([
					/<!--[\s\S]+?-->/gi,                                         // Word comments
					/<\/?(img|font|meta|link|style|span|div|v:\w+)[^>]*>/gi,     // Remove some tags including VML content
					/<\\?\?xml[^>]*>/gi,                                         // XML namespace declarations
					/<\/?o:[^>]*>/gi,                                            // MS namespaced elements <o:tag>
					/ (id|name|class|language|type|on\w+|v:\w+)=\"([^\"]*)\"/gi, // on.., class, style and language attributes with quotes
					/ (id|name|class|language|type|on\w+|v:\w+)=(\w+)/gi,        // on.., class, style and language attributes without quotes (IE)
					[/<(\/?)s>/gi, '<$1strike>'],                                // Convert <s> into <strike> for line-though
					/<script[^>]+>[\s\S]*?<\/script>/gi                          // All scripts elements for msoShowComment for example
				]);
    	  
    	}

    	return (text);
    },
  
    getAttrs: function(string){
      var result;
      var attrs = {};
      var pattern = /(\w+)=(["']{1})([^\2]*?)(\2{1})/g;
      while((result = pattern.exec(string)) != null){
        attrs[result[1].toLowerCase()] = result[3];
      }
      return attrs;
    },
    
    getParams: function(string){
      var result;
      var params = {};
      var pattern = /<(param)+([^\/>]*|[^>]*)\/?>(<\/? ?\1>)?/gi;
      while((result = pattern.exec(string)) != null){
        var attrs = b_editor.regexp.getAttrs(result[2]);
        params[attrs.name] = attrs.value;
      }
      return params;
    }
  }

})(jQuery);


(function($) {

  if(!this.b_editor)
    this.b_editor = {};
    
  this.b_editor.embed = {
    box: {
      width: 400,
      height: 300
    },
    allow: [
      "movie",
      "allowFullScreen",
      "allowscriptaccess",
      "wmode",
      "flashVars"
    ],
    
    isAllow: function(name){
      for (var i=0; i < this.allow.length; i++) {
        if(this.allow[i].toLowerCase() == name.toLowerCase())
          return true;
      };
      return false;
    },
    
    ObjectToData: function(object){
      if(object){
        
        if(typeof object == "object")
          object = $(object).clone().wrap("<div>").parent().html();
          
        var data = new Object();
        object = b_editor.regexp.cleanup(object);
        var _object = object.match(/<(object)([^>]*)>(.*?)(<\/ ?\1>)/i);
        
        
        if(_object){ // если к нам пришел правильный object
          
          var attrs = b_editor.regexp.getAttrs(_object[2]); // получаем значения атрибутов
          var params = b_editor.regexp.getParams(_object[3]);
          if(params.movie.length || attrs.src.length){ // если правильно пришла ссылка на мувик
            data.box = {
              width: attrs.width*1,
              height: attrs.height*1
            }

            if(!data.box.width) data.box.width = this.box.width;
            if(!data.box.height) data.box.height = this.box.height;

            data.params = {}
            for(name in params){
              if(b_editor.embed.isAllow(name)){
                data.params[name.toLowerCase()] = params[name];
              }
            }

            if(data.params.movie)
              data.url = data.params.movie
            else
              data.url = attrs.src;
              
            return data;
            
          }

        }
        return false;

      }

      return false;
    },
    
    DataToObject: function(data){
      if(!data.box.width) data.box.width = this.box.width;
      if(!data.box.height) data.box.height = this.box.height;

      var embed = '<object src="' + data.url + '" width="' + data.box.width + '" height="' + data.box.height + '">';
      for(name in data.params){
        if(b_editor.embed.isAllow(name))
          embed += '<param name="' + name + '" value="' + data.params[name] + '"></param>'
      }
      embed += "</object>";
      return embed;
    },
    
    JSONtoData: function(json){
      try{

        var data = eval("(" + json + ")");
        if(data.url){
          if(!data.box.width) data.box.width = this.box.width;
          if(!data.box.height) data.box.height = this.box.height;
          return data;
        } else return false;

      }catch(e){}

      return false;
    },
    
    print: function(obj){
      var string = "{ ";
        for(prop in obj){
          string += prop + ": ";
          switch(typeof obj[prop]){
            case "object":
              string += this.print(obj[prop]);
              break;
            case "number":
              string += obj[prop];
              break;
            default:
              string += "'" + obj[prop] + "'";
              break;
          }
          string += ", ";
        }
        string = string.slice(0, -2);
        
      string += " }";

      return string;
    }
    
  }

})(jQuery);

(function( $ ){
  
  this.IncrementalSearcherMap = {
    is: {
      init: false
    },
    create: function( map ){
      if(map && (map.length != 0)){
        this.is.init = true;
        this.map = map;
      }
    },
    isInit: function(){
      if( this.is.init )
        return true;
      
      return false;
    },
    
    get: function(){
      return this.map;
    }
  };
  
  this.IncrementalSearcher = _Class.extend({
    init: function( id, data ){
      this.inputNode = $(id);
      if(!this.inputNode.length) this.inputNode = $("#" + id);
      if(!this.inputNode.length) return false;

      this.dataArray = data;
      if(IncrementalSearcherMap.isInit())
        this.dataMap = IncrementalSearcherMap.get();

      this.bindEvents();
      
    },
    
    bindEvents: function(){
      var self = this;
      var timer;
      this.inputNode
        .keyup(function(){
          if(timer) clearTimeout(timer);
          timer = setTimeout(function(){
            self.onsearch();
          }, 300);
          
        })
        .change(function(){
          if(timer) clearTimeout(timer);
          timer = setTimeout(function(){
            self.onsearch();
          }, 300);
        })
    },
    
    onsearch: function(){
      var value = this.getValue();
      
      for ( var i=0; i < this.dataArray.length; i++ ) {
        var objectIds = this.dataArray[i][0];
        var searchData = this.dataArray[i][1].toLowerCase();
        
        if( searchData.indexOf(value) != -1 ){
          // found something –> show object(s)
          this.each(objectIds, function( id ){
            var node = document.getElementById(id);
            if( node ){
              $(node).show();
              this.map( id, true );
            }
          })
        } else {
          // nothing –> hide object(s)
          this.each(objectIds, function( id ){
            var node = document.getElementById(id);
            if( node ){
              $(node).hide();
              this.map( id, false );
            }
          })
        }
        
      };
      
      this.filterByMap();
      
    },
    
    map: function( id, action ){
      function getVisible( object ){
        var visible = 0;
        for( id in object ) if( object[id] ) visible++;
        return visible;
      };

      if( this.dataMap )

        for ( var i=0; i < this.dataMap.length; i++ )
          // we are root
          if( this.dataMap[i].id == id ){
            this.dataMap[i].show = action;
            if( this.dataMap[i].children )
              this.dataMap[i].visible = getVisible( this.dataMap[i].children );
            
          // we are child
          } else if ( this.dataMap[i].children && this.dataMap[i].children[id] != undefined ){
            this.dataMap[i].children[id] = action;
            this.dataMap[i].visible = getVisible( this.dataMap[i].children );
          }
      
    },
    
    filterByMap: function( data ){
      if( this.dataMap )

        for ( var i=0; i < this.dataMap.length; i++ ) {
          if( !this.dataMap[i].node ){
            this.dataMap[i].node = document.getElementById(this.dataMap[i].id);
            if( this.dataMap[i].node ) this.dataMap[i].node = $(this.dataMap[i].node);
            else break;
          }

          if( this.dataMap[i].show && this.dataMap[i].visible ) // show
            this.dataMap[i].node.show();

          else // hide
            this.dataMap[i].node.hide();
        };

    },
    
    each: function( ids, callback ){
      switch( typeof ids ){
        case 'string':
          callback.call(this, ids);
          break;
        case 'array':
          for (var i=0; i < ids.length; i++) {
            callback.call(this, ids[i]);
          };
          break;
      }
    },
    
    getValue: function(){
      return this.inputNode.val().toLowerCase();
    }
  })
  
  
})( jQuery );

(function( $ ){
  
  this.AjaxSearcher = _Class.extend({
    
    init: function( nodeId, allow ){
      this.formNode = $(nodeId);
      this.inputNodes = this.formNode.find("input");
      this.queries = { };
      if( allow && allow.length )
        this.allowQueries = allow;
      this.bindEvents();
    },
    
    bindEvents: function(){
      var self = this;
      var timer;
      this.inputNodes
        .keyup(function(){
          var node = this;
          var query = self.checkQuery();
          if( query ){
            self.preload( $(node) );
            
            if(timer) clearTimeout(timer);
            timer = setTimeout(function(){
              self.onsearch( node );
            }, 1000);
          }
        })

        .change(function(){
          var node = this;
          var query = self.checkQuery();
          if( query ){
            self.preload( $(node) );
            
            if(timer) clearTimeout(timer);
            timer = setTimeout(function(){
              self.onsearch( node );
            }, 1000);
          }
        })
    },
    
    checkQuery: function(){
      var self = this;
      var ajax = false;
      
      this.inputNodes.each(function( i ){
        var input = $(this);
        var uid = "val" + i;
        if( self.queries[uid] == undefined || (self.queries[uid] != input.val()) ){
          self.queries[uid] = input.val();
          ajax = true;
        }
      })
      
      return ajax;
    },
    
    onsearch: function( inputNode ){
      var self = this;
      inputNode = $(inputNode);
      
      this.preload( inputNode );
      $.get(this.formNode.attr("action"), this.formNode.serialize(), function(){
        self.preload( false );
      }, "script");
    },
    
    preload: function( node ){
      if(node === false)
        this.inputNodes.each(function(){
          $(this).parents(".bb-forms-string").removeDependClass("loading");
        })

      else
        node.parents(".bb-forms-string").addDependClass("loading");
    }
    
    
  });
  
})( jQuery );
var Activity = {
  types: ['all', 'photos', 'events', 'micros', 'posts'],
  current_type: "all",
  current_favorites: false,
  init: function(){
    /*var pechenice = jQuery.cookie("activity_filter");
    if(pechenice) {
      this.current_type = pechenice;
    }*/
    this.filters = jQuery(".j-activity-filters");
    this.filters.find("a").each(function(i, e){
      jQuery(e).click(function(){
        Activity.filter(Activity.types[i]);
        return false;
      });
    });

    this.container = jQuery(".activity-container");

    this.filter(this.current_type);
  },
  highlight: function(type){
    this.filters.find("li").removeClass("selected");
    var selector = this.filters.find("li").get(jQuery.inArray(type, this.types));
    jQuery(selector).addClass("selected");
  },
  show_all: function(){
    return jQuery(".j-activity").show();
  },
  filter: function(type){
    type = typeof(type) == 'undefined' ? this.current_type : type;

    //jQuery.cookie("activity_filter", type);
    this.current_type = type;
    this.highlight(type);
    this.update_container_class();    
    if(type == "all"){this.show_all();}
    else{
      jQuery(".j-activity:not(.j-activity-" + type + ")").hide();
      jQuery(".j-activity-" + type).show();
    }
    this.delete_ephemeral();
    this.update_activity_dates();
    this.filter_favorites();
    this.ajust_loader();
  },
  update_activity_dates: function(){
    if(this.current_type == "all"){
      jQuery(".activity-date").show();
    }else{
      jQuery(".activity-date").hide();
    }
  },
  filter_favorites: function(){
    if(this.current_favorites){
      jQuery(".j-activity:not(.j-activity-favorite)").hide();
    }
  },
  change_favorites: function(show){
    this.current_favorites = show;
    this.filter();
  },
  update_container_class: function(){
    _me = this;
    this.types.each(function(e, i){
      _me.container.removeClass("activity-container_"+e);
    });
    _me.container.addClass("activity-container_" + this.current_type);
  },
  delete_ephemeral: function(){
    jQuery(".j-activity-ephemeral").remove();
  },
  count: function(type){
    type = typeof(type) == 'undefined' ? this.current_type : type;
    var count;
    if(type == "all"){count = jQuery(".j-activity").length;}
    else{count = jQuery(".j-activity-" + type).length;}
    return count;
  },
  load_more_activity:function(){
    if(this.loading){return false;}
    this.loading = true;
    jQuery(".activity-show-more").find("img").show();
    jQuery.getJSON("/activity/index.json", {offset:this.count(), type: this.current_type, limit: 50}, function(res){
      jQuery(".activity-container").append(res.activities);
      if(!res.more){jQuery(".activity-show-more").hide();}
      Activity.loading = false;
      jQuery(".activity-show-more").find("img").hide();
    });
  },
  ajust_loader: function(){
    jQuery(".activity-show-more").show();
    jQuery(".activity-show-more").find("img").hide();
  }
}

jQuery(function() {
  Activity.init();
  if (jQuery.inArray(window.location.hash.slice(1), Activity.types) >= 0){
    Activity.filter(window.location.hash.slice(1));
  }
  // Показываем активность только после всех приготовлений
  jQuery(".activity-container").css('visibility', 'visible');
});
/* Comments in right micro block */

(function($) {

	$(document).ready(function(){
		if($('.b-micro-list .b-micro-bubble .b-comment-counter').length !=0){
	  	micro.comments.init();
		}
	});
	
	if(!this.micro)
    this.micro = new Object();
  
	this.micro.comments = {
		init:function(){
			var _my = this;
			this.toggleButton = $('.b-micro-list .b-micro-bubble .b-comment-counter');
			this.toggleButton.click(function(){
				_my.toggleComments($(this));
			});
		},
    update_micro_block: function(micro_id){
      var micro_block = jQuery(micro_id);
      var count = micro_block.find(".b-comment-counter span");
      count.html(parseInt(count.html(), 10) + 1);
      micro_block.find("textarea").attr('disabled', false).attr('value', '');
    },
		toggleComments:function(button){
			if($('.j-comments-open').length != 0){
				// alert(1324)
				$('.comments-container').slideUp('fast');
			}
			var comments = button.parents('.b-micro-bubble').find('.comments-container');
			if(!comments.is('.j-comments-open')){
				comments.addClass('j-comments-open');
				comments.slideDown('fast');
			} else {
				comments.removeClass('j-comments-open');
				comments.slideUp('fast');
			}
		}
	}


})(jQuery);

/* Comments in right micro block (end) */
/* Choose city bubble */

(function($) {
	
	this.ChooseCity = function(){
		this.init();
	}
	
	ChooseCity.prototype = {
		init:function(){
			var _my = this;
			this.alphabet = $('.choose_city_alphabet span');
			this.cities = $('.choose_city_columns li a');
			this.alphabet.click(function(){
				_my.toggleCities(jQuery(this));
			})
		},
		toggleCities:function(span){
			var selected = span.attr('class');
			if(span.is('.j-cities-filter-all')){
				for(var i=0; i<this.cities.length; i++){
					this.cities.eq(i).removeClass('shadowed');
				}
			} else {
				for(var i=0; i<this.cities.length; i++){
					if(this.cities.eq(i).is('.'+selected)){
						this.cities.eq(i).removeClass('shadowed');
					} else {
						this.cities.eq(i).addClass('shadowed');
					}
				}
			}
		}
	}
	
	

})(jQuery);

/* Choose city bubble */
// Переключалка деталей на странице лука
function change_look_image(id, path) {
  jQuery(".b-look-details .item").removeClass("active");
  jQuery("#look_image_" + id).addClass("active");
  jQuery(".b-look #look_image").attr("src", path);
}
(function( $ ){
	$(document).ready(function(){
		LookSWFUpload.init_uploader();
		LookDetailsSWFUpload.init_uploader();
	});

	var Loo