
(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, '');
    };
  }

  if( typeof(Array.prototype.uniq) === "undefined" ) {
    Array.prototype.uniq = function() {
      var o = {}, i, l = this.length, r = [];
      for(i=0; i<l;i++) o[this[i]] = this[i];
      for(i in o) r.push(o[i]);
      return r;
    };
  }


})(jQuery);

function setGivenchyCookie(){
	jQuery.cookie('givenchy_status', 'on');
}

function deleteGivenchyCookie(){
	jQuery.cookie('givenchy_status', null);
}

// 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].trim();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.indexOf(f[h])==-1){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.trim()});return e.length>0?e[e.length-1]:""},setValue:function(e){var g=this.input.val().split(",").map(function(h){return h.trim()});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+"?q="+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(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);


(function($) {

	$.fn.serializeOnly = function(){
	  var form = this.serializeArray();
	  var result = new Array()
	  for (var i=0; i < form.length; i++) {
	    for( var j=0; j < arguments.length; j++ ){
	     if( form[i].name == arguments[j] )
	      result.push(form[i]);
	    };
	   
	  };
	  
    return jQuery.param( result );
	};

})( jQuery );
/* Global browsers definition */

(function($) {
  
  if( !$.browser.msie ) $(document.documentElement).addClass("e-loaded");

  // default browser detection
	if( $.browser.safari ) $(document.documentElement) .addClass("e-webkit");
	if( $.browser.mozilla ) $(document.documentElement).addClass("e-gecko");
	if( $.browser.opera ) $(document.documentElement).addClass("e-opera");

  // mac browser detection
	var isMac = navigator.userAgent.indexOf('Mac') != -1;
	if(isMac){
	  $(document.documentElement).addClass("e-mac");
  	if( $.browser.safari ) $(document.documentElement) .addClass("e-webkit-mac");
  	if( $.browser.mozilla ) $(document.documentElement).addClass("e-gecko-mac");
  	if( $.browser.opera ) $(document.documentElement).addClass("e-opera-mac");
	}

})(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}}}}}();
/*
* Код динамического обновления счетчика LiveInternet
* Исходный код - http://support.li.ru/tmp/ajax-li.txt
* Исправлено в Look At Me для явной установки отслеживаемого урла
* */
function updateLiveInternetCounter(url){
  var countingURL = "";
  if(url){
    countingURL = url;
  }else{
    countingURL = document.URL;
  }
	var liCounter = new Image(1,1);
	liCounter.src = 'http://counter.yadro.ru/hit?r='+
	((typeof(screen)=='undefined')?'':';s'+screen.width+
	'*'+screen.height+'*'+(screen.colorDepth?screen.colorDepth:
	screen.pixelDepth))+';u'+escape(countingURL)+
	';'+Math.random();
}

/*
  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 );
/*
*
* jRails ajax extras
* version 0.1
* <aaron@ennerchi.com> | http://www.ennerchi.com
*
*/

(function($) {
	$.ajaxSettings.accepts._default = "text/javascript, text/html, application/xml, text/xml, */*";
})(jQuery);


/*
*
* jRails form extras
* <aaron@ennerchi.com> | http://www.ennerchi.com
*
*/


(function($) {
	// reset a form
	$.fn.reset = function() {
		return this.each(function() {
			// guard against an input with the name of 'reset'
			// note that IE reports the reset function as an 'object'
			if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
				this.reset();
		});
	};
	// enable a form element
	$.fn.enable = function() {
		return this.each(function() {
			this.disabled = false;
		});
	};
	// disable a form element
	$.fn.disable = function() {
		return this.each(function() {
			this.disabled = true;
		});
	};

})(jQuery);

/*
*
* jRails form observer plugin
* version 0.2
* <aaron@ennerchi.com> | http://www.ennerchi.com
*
*/

(function($) {
	$.extend({ // Translate field to event
		fieldEvent: function(el, obs) {
			var field = el[0] || el, e = 'change';
			if (field.type == 'radio' || field.type == 'checkbox') e = 'click';
			else if (obs && (field.type == 'text' || field.type == 'textarea' || field.type == 'password')) e = 'keyup';
			return e;
		}
	});
	$.fn.extend({ // Delayed observer for fields and forms
		delayedObserver: function(delay, callback){
			var el = $(this);
			if (typeof window.delayedObserverStack == 'undefined') window.delayedObserverStack = [];
			if (typeof window.delayedObserverCallback == 'undefined') {
				window.delayedObserverCallback = function(stackPos) {
					var observed = window.delayedObserverStack[stackPos];
					if (observed.timer) clearTimeout(observed.timer);
					observed.timer = setTimeout(function(){
						observed.timer = null;
						observed.callback(observed.obj, observed.obj.formVal());
					}, observed.delay * 1000);
					observed.oldVal = observed.obj.formVal();
				};
			}
			window.delayedObserverStack.push({
				obj: el, timer: null, delay: delay,
				oldVal: el.formVal(), callback: callback
			});
			var stackPos = window.delayedObserverStack.length-1;
			if (el[0].tagName == 'FORM') {
				$(':input', el).each(function(){
					var field = $(this);
					field.bind($.fieldEvent(field, delay), function(){
						var observed = window.delayedObserverStack[stackPos];
						if (observed.obj.formVal() == observed.oldVal) return;
						else window.delayedObserverCallback(stackPos);
					});
				});
			} else {
				el.bind($.fieldEvent(el, delay), function(){
					var observed = window.delayedObserverStack[stackPos];
					if (observed.obj.formVal() == observed.oldVal) return;
					else window.delayedObserverCallback(stackPos);
				});
			};
		},
		formVal: function() { // Gets form values
			var el = this[0];
			if(el.tagName == 'FORM') return this.serialize();
			if(el.type == 'checkbox' || el.type == 'radio') return this.filter('input:checked').val() || '';
			else return this.val();
		}
	});
})(jQuery);

/*
*
* jRails visual effects stubs
* version 0.2
* <aaron@ennerchi.com> | http://www.ennerchi.com
*
*/

(function($) {
	$.fn.extend({
		visualEffect : function(o, options) {
			if (options) {
        speed = options.duration * 1000;
      } else {
        speed = null;
      }
			e = o.replace(/\_(.)/g, function(m, l){return l.toUpperCase()});
			return eval('$(this).'+e+'('+ speed + ')');
		},
		appear : function(speed, callback) {
			return this.fadeIn(speed, callback);
		},
		blindDown : function(speed, callback) {
			return this.show('blind', { direction: 'vertical' }, speed, callback);
		},
		blindUp : function(speed, callback) {
			return this.hide('blind', { direction: 'vertical' }, speed, callback);
		},
		blindRight : function(speed, callback) {
			return this.show('blind', { direction: 'horizontal' }, speed, callback);
		},
		blindLeft : function(speed, callback) {
			this.hide('blind', { direction: 'horizontal' }, speed, callback);
			return this;
		},
		dropOut : function(speed, callback) {
			return this.hide('drop', {direction: 'down' }, speed, callback);
		},
		dropIn : function(speed, callback) {
			return this.show('drop', { direction: 'up' }, speed, callback);
		},
		fade : function(speed, callback) {
			return this.fadeOut(speed, callback);
		},
		fadeToggle : function(speed, callback) {
			return this.animate({opacity: 'toggle'}, speed, callback);
		},
		fold : function(speed, callback) {
			return this.hide('fold', {}, speed, callback);
		},
		foldOut : function(speed, callback) {
			return this.show('fold', {}, speed, callback);
		},
		grow : function(speed, callback) {
			return this.show('scale', {}, speed, callback);
		},
		highlight : function(speed, callback) {
			return this.show('highlight', {}, speed, callback);
		},
		puff : function(speed, callback) {
      alert("puff");
			return this.hide('puff', {}, speed, callback);
		},
		pulsate : function(speed, callback) {
			return this.show('pulsate', {}, speed, callback);
		},
		shake : function(speed, callback) {
			return this.show('shake', {}, speed, callback);
		},
		shrink : function(speed, callback) {
			return this.hide('scale', {}, speed, callback);
		},
		squish : function(speed, callback) {
			return this.hide('scale', { origin: ['top', 'left'] }, speed, callback);
		},
		slideUp : function(speed, callback) {
			return this.hide('slide', { direction: 'up'}, speed, callback);
		},
		slideDown : function(speed, callback) {
			return this.show('slide', { direction: 'up'}, speed, callback);
		},
		switchOff : function(speed, callback) {
			return this.hide('clip', {}, speed, callback);
		},
		switchOn : function(speed, callback) {
			return this.show('clip', {}, speed, callback);
		}
	});
})(jQuery);

/*
 *
 */
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">скрыть</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(){
  $(document).ready(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 );


(function($) {
  
  var OPTIONS = {
    rootSelector: ".b-comments",
    formSelector: ".bc-form",
    commentSelector: ".bc-comment",
    insertSelector: ".bc-comment-container",
    preloadClass: "bc-preloading",
    dummyClass: "bc-dummy"
  }
  
  this.b_comments = {
    form: function( node, event ){
      var obj = $(node);
      var root = obj.parents(OPTIONS.rootSelector);
      var form = root.find(OPTIONS.formSelector);
      
      var dummy = root.find("." + OPTIONS.dummyClass);
      if( !dummy.length ){ /* create dummy for real place of form and attach cancel event */
        dummy = $("<div>").addClass(OPTIONS.dummyClass); form.after(dummy);
        form.find(".cancel").click(function(){
          form.find("input[type=hidden]").eq(0).removeAttr('value');
          form.find("textarea").val("");
          dummy.before(form);
          dummy.remove();
          return false;
        });
      }

      var comment = obj.parents(OPTIONS.commentSelector).eq(0);
      comment.find(OPTIONS.insertSelector).eq(0).after(form);
      form.find("input[type=hidden]").eq(0).val(comment.attr("id").replace('comment_', ''));
      form.find("textarea").focus();
      return false;
    },
    
    preload: function( node ){
      var form = $(node).parents(OPTIONS.rootSelector).find(OPTIONS.formSelector);
      form.find("button").get(0).buttonHandler.state("disabled", true);
      form.find(".cancel").hide();

      var preload = $('<div>').addClass(OPTIONS.preloadClass);
      var field = form.find("textarea");
      var formOffset = form.offset();
      var fieldOffset = field.offset();

      field.after(preload);
      preload.css({ opacity: 0, left: fieldOffset.left-formOffset.left, top: fieldOffset.top-formOffset.top-1, width: field.outerWidth(), height: field.outerHeight() })
        .animate({ opacity: 0.8 });
    },
    
    success: function( node ){
      var root = $(node).parents(OPTIONS.rootSelector);
      var form = root.find(OPTIONS.formSelector);

      form.find("." + OPTIONS.preloadClass).remove();
      form.find("textarea").val("");
      form.find("input[type=hidden]").eq(0).removeAttr('value');
      form.find("button").get(0).buttonHandler.state("disabled", false);
      form.find(".cancel").removeAttr("style");

      var dummy = root.find("." + OPTIONS.dummyClass);
      if( dummy.length ){
        dummy.before(form);
        dummy.remove();
      }
    },

    update_comment_counters: function(resource_dom_id, new_count){
      //console.log($(OPTIONS.rootSelector).find("a .j-header-comments-count"));
      $(".j-comments-count-" + resource_dom_id).html(new_count);
    }

  }

})(jQuery);


(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;
        }).addDependClass("disabled");
        this.navigation.eq(1).click(function(){
          self.show(1);
          return false;
        })
      }
      
      if( this.options.click ){
        this.dayNodes.find("a").click( this.options.click );
      }
    },
    
    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).addDependClass("disabled");
      else
        this.navigation.eq(0).removeDependClass("disabled");

      if( current.eq(current.length-1).next().is("." + this.options.navigation) )
        this.navigation.eq(1).addDependClass("disabled");
      else
        this.navigation.eq(1).removeDependClass("disabled");

    }
    
  })
  
  
})( jQuery );

(function( $ ){
  
  $(document).ready(function(){
    GLOBAL.reInit(function(){
      var top = $(".b-movie-top-init").removeClass("b-movie-top-init");
      var min = top.find(".min");
      var max = top.find(".max");
      min.show(); max.hide();
      var minH = top.height();
      if ( !$.browser.safari && !$.browser.opera && !$.browser.msie )
        minH++;
      min.hide(); max.show();
      var maxH = top.height();
      var state = $.cookie("movie_top") || "min"
      if( state == "min"){
        min.show(); max.hide();
      } else {
        min.hide(); max.show();
      }

      if( top ){

        min.find("table th").click(function(){
          top.animate({ height: maxH }, "fast");
          min.css({ zIndex: 1, position: "absolute", left: 0, top: 0, opacity: 1 }).show().animate({ opacity: 0 }, function(){
            $(this).removeAttr("style").hide();
          });
          max.css({ zIndex: 2, position: "absolute", left: 0, top: 0, opacity: 0 }).show().animate({ opacity: 1 }, function(){
            $(this).removeAttr("style");
            top.removeAttr("style");
            $.cookie("movie_top", "max");
          });
        })

        max.find(".close").click(function(){
          top.animate({ height: minH }, "fast");
          max.css({ zIndex: 1, position: "absolute", left: 0, top: 0, opacity: 1 }).show().animate({ opacity: 0 }, function(){
            $(this).removeAttr("style").hide();
          });
          min.css({ zIndex: 2, position: "absolute", left: 0, top: 0, opacity: 0 }).show().animate({ opacity: 1 }, function(){
            $(this).removeAttr("style")
            top.removeAttr("style");
            $.cookie("movie_top", "min");
          });
        })


      }
    });
  });
  
})( 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 = {
    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 );

(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 = { };
      this.queue = [];
      if( allow && allow.length )
        this.allowQueries = allow;
      this.bindEvents();
    },
    
    bindEvents: function(){
      var self = this;
      var timer;
      this.formNode.submit(function(){
        return false;
      })
      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);
          }
        })
        
        .each(function(){
          // хуйня вот здесь, нельзя такие проверки писать в классе
          // но пока по-другому не придумал
          if( $(this).attr("type") != "hidden" && $(this).val().length )
            self.onsearch( this );
        })
      
      
    },
    
    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 );
      var index = this.queue.length;

      this.bindQueue({
        ajax: $.ajax({
          type: "GET",
          dataType: "text",
          url: this.formNode.attr("action"),
          data: this.formNode.serialize(),
          success: function( script ){
            if( !self.queue[index].abort ){
              eval(script);
              self.preload( false );
              GLOBAL.reInit();
            }
          },
          error: function(){
            self.preload( false );
          }
        })
      });
      
    },
    
    bindQueue: function( query ){
      for (var i=0; i < this.queue.length; i++) {
        this.queue[i].abort = true;
      };
      
      this.queue.push( query );
    },
    
    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 );

(function($){
  this.Comments = {
    actualize_rating: function(actual_rating_array){
      $.each(actual_rating_array, function(){
        jQuery('#' + this[0] + " ins").html(this[1]);
        if(!this[2]){jQuery('#' + this[0]).addClass("bc-comment-rating-hide");}        
      });
    },
    as_seen_by: function(status){
      switch (status) {
      case 'admin':
        jQuery(".b-comments .bc-comment .detalize-comment-votes").show();
        jQuery(".b-comments .bc-comment .comment-toggle").show();
        jQuery(".b-comments .bc-comment-deleted").show();
        break;
      case 'editor':
        jQuery(".b-comments .bc-comment .comment-toggle").show();
        jQuery(".b-comments .bc-comment-deleted").show();
        break;      
      }
    }
  }

  $(document).ready(function(){
    $(".comment-toggle").click(function(){
      var obj = $(this);
      var id = obj.attr("id").replace(/\D+/, "");

      obj.fadeOut();
      $.post('/comments/' + id + "/toggle", function(){
        obj.fadeIn();

        if(obj.is(".comment-toggle-removed")){
          $('#comment_' + id).find('.bc-comment').andSelf().removeClass('bc-comment-deleted');
        } else {
          $('#comment_' + id).addClass('bc-comment-deleted');
        }
        obj.toggleDependClass("removed");

      });
      
      
    })

  });
  
})( 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;
    jQuery.each( this.types, function(i, e) {
      _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);
}
/*global jQuery, Draggable, _back, _mark, d, document, jsButton, oThis, sClass, window*/

var Calendar = classDraggable.extend({
	_default: { //current date
		year: (new Date()).getFullYear(),
		month: (new Date()).getMonth()+1,
		submit: "."
	},
	oninit: function(){
		var oThis = this;
		this.hSetting = {};
		jQuery.extend(this.hSetting, this._default, arguments[1] ? arguments[1] : {});

		jQuery.extend(this.is, {
			animate: false,
			controls: false,
			controlsState: false
		});

		function getDateText(date){
			return date.getDate() + ' ' + oThis.months.second[date.getMonth()] + ', ' + oThis.week_days[date.getDay()];
		}
		
		this.months = {
			first: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
			second: ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря']
		};
		this.week_days = ['воскресенье', 'понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота'];
		
		this.aMonths = [];
		
		this.ptr.append("<div class='calendar-current'>" + getDateText(new Date()) + "</div>");
		this.ptr.append(
			"<div class='calendar-body'>" +
				"<div class='calendar-button calendar-button-left'><i></i></div>" +
				"<div class='calendar-button calendar-button-right'><i></i></div>" +
				"<div class='calendar-week'></div>" +
			"</div>");
		this.ptr.append(
			"<div class='calendar-controls'><div class='calendar-control-in'>" +
				"<span class='calendar-clear'>Отменить</span>" +
				"<button type='submit' id='editor_submit' class='b-button_form' buttontype='simple'>" +
				  "<div class='b-button'>" +
				    "<table><tbody><tr><td>" +
				      "<div class='b-button-bg'>" +
				        "<i class='l g-png'/><i class='r g-png'/>" +
				      "</div>" +
				      "<div attachdata='value' class='b-button-text'>" +
				        "<i class='b-button-icon g-png'/>" +
				        "Показать" +
				      "</div>" +
				    "</td></tr></tbody></table>" +
				  "</div>" +
				"</button>" +
			"</div></div>");

		this.ptr.append(
			'<form class="calendar-form" method="post" action="' + this.hSetting.submit + '">' +
				'<input type="hidden" name="dates" />' +
				'<input type="hidden" name="month" />' +
				'<input type="hidden" name="year" />' +
			'</form>');
		
		this.ptr = this.ptr.find("div.calendar-body");
		var curr = this.createMonth(this.hSetting);
		this.ptr.append(curr.ptr);

		if(curr.count > 35) {
			this.ptr.css({ height: 180 });
		}
			
		curr.current = true;
		this.aMonths.push(curr);
		this.redraw(curr);
		b_button_init();
		this.resize();
	},
	resize: function(){
		var _offset = this.ptr.offset();

		this.current = this.getCurrent();
		for(var key in this.current.items){
			var ptr = this.current.items[key].ptr;
			var _o = ptr.offset();
			this.current.items[key].left = _o.left - _offset.left;
			this.current.items[key].top = _o.top - _offset.top;
		}
		
		this.cx = _offset.left;
		this.cy = _offset.top;
	},
	events: function(){
		var oThis = this;
		this.ptr.find("div.calendar-button").mousedown(function(){
			jQuery(this).addClass("calendar-button-down");
		}).mouseup(function(evt){
			jQuery(this).removeClass("calendar-button-down");
			if(!oThis.is.animate) {
				oThis.onclick(this, evt);
			}
		});

		jQuery(document)
			.mousemove(function(evt){
				oThis._onmousemove(evt);
				return false;
			});

		var jsbutton = this.ptr.parents("div.calendar").find("button").click(function(){
			var form = oThis.ptr.parents("div.calendar").find("form.calendar-form");
			
			var dates = '';
			for (var i=0; i < oThis.aMonths.length; i++) {
				for(var k in oThis.aMonths[i].items){
					if(oThis.aMonths[i].items[k].selected){
						var d = new Date(k);
						dates += oThis.dateString(d) + ',';
					}
				}
			}
			dates = dates.replace(/,$/, '');
			
			var curr = oThis.getCurrent();
			form.
				find("input[name='dates']").val(dates);
			form.
				find("input[name='month']").val(curr.date.getMonth()+1);
			form.
				find("input[name='year']").val(curr.date.getFullYear());
			
			track_event('Calendar', 'Click to show');
			form.submit();
		
		});
		
		this.ptr.parents("div.calendar").find("span.calendar-clear").click(function(){
			oThis.empty();
			oThis.redraw(oThis.getCurrent());
		});
		
		jQuery(window).resize(function(){
			oThis.resize();
		});
		
		this.oArrow = this.ptr.parents("div.calendar").find("div.calendar-week").click(function(evt){
			oThis.selectByWeek(evt);
		});
	},
	onmousedown: function(evt){
		this.resize();
		
		var _s = this.getDay(this.current, evt.pageX-this.cx, evt.pageY-this.cy);
		if(_s){
			if(!evt.shiftKey) {
				this.empty(this.current);
			}

			this.start = new Date(_s);

			var curr = this.current.items[_s];
			if(curr.selected){
				curr.ptr.removeClass("selected");
				curr._selected = false;
				this.remove = true;
			} else {
				curr.ptr.addClass("selected");
				curr._selected = true;
				this.remove = false;
			}
			this.redraw(this.current);
			this.is.controls = true;
		}
	},
	_onmousemove: function(evt){
		var week = this.getWeek(this.current, evt.pageY - this.cy);
		if(week) {
			this.oArrow.css({ left: week.left-20, top: week.top }).show();
		} else {
			this.oArrow.hide();
		}
	},
	onmousemove: function(evt, x, y){
		function _mark(curr, obj){
			if(obj.remove){
				curr.ptr.removeClass("selected");
				curr._selected = false;
			} else {
				curr.ptr.addClass("selected");
				curr._selected = true;
			}
		}

		function _back(curr){
			curr._selected = curr.selected;
			if(curr.selected) {
				curr.ptr.addClass("selected");
			} else {
				curr.ptr.removeClass("selected");
			}
		}

		if(this.start){
			this.end = new Date(this.getDay(this.current, x, y));
			for(var k in this.current.items){
				var d = new Date(k);
				var curr = this.current.items[k];
				if(this.start < this.end) {
					if(d >= this.start && d <= this.end) {_mark(curr, this);}
					else{ _back(curr);}
				} else {
					if(d <= this.start && d >= this.end) {_mark(curr, this);}
					else {_back(curr);}
				}
			}
			this.redraw(this.current);
		}
	},
	onmouseup: function(){
		for(var k in this.current.items){
			var curr = this.current.items[k];
			curr.selected = curr._selected ? curr._selected : false;
		}
		this.redraw(this.current);
		
		if(this.is.controls) {
			this.showControls();
		}
		
		this.start = null;
		this.end = null;
	},
	onclick: function(obj, evt){
		function setCurrent(month){
			for (var i=0; i < oThis.aMonths.length; i++) {
				oThis.aMonths[i].current = false;
			}
			month.current = true;
		}
		function exist(hDate){
			var date = new Date(hDate.year, hDate.month-1);
			for (var i=0; i < oThis.aMonths.length; i++) {
				if(oThis.aMonths[i].date.valueOf() == date.valueOf()) {
					return true;
				}
			}
			return false;
		}
		
		function getMonth(hDate){
			var date = new Date(hDate.year, hDate.month-1);
			for (var i=0; i < oThis.aMonths.length; i++) {
				if(oThis.aMonths[i].date.valueOf() == date.valueOf()) {
					return oThis.aMonths[i];
				}
			}
		}
		var oThis = this;
		this.is.animate = true;
		
		var direction = 1;
		if(jQuery(obj).is(".calendar-button-left")) {
			direction = -1;
		}
		
		this.current = this.getCurrent();
		this.current.ptr.css({ position: "absolute", left: 0, top: 0 });
		var date = new Date(this.current.date.getFullYear(), this.current.date.getMonth()+direction);
		var newMonth = { year: date.getFullYear(), month: date.getMonth()+1 };
		if(!exist(newMonth)){
			newMonth = this.createMonth(newMonth);
			newMonth.ptr.css({ position: "absolute", left: direction*240, top: 0 });
			this.ptr.append(newMonth.ptr);
		} else {
			newMonth = getMonth(newMonth);
		}

		this.redraw(newMonth);

		newMonth.ptr.show();
		this.current.ptr.animate({ left: -1*direction*240 }, function(){
			jQuery(this).hide();
		});
		newMonth.ptr.animate({ left: 0 }, function(){
			oThis.is.animate = false;
		});
		if(newMonth.count != this.current.count){
			if(this.current.count < newMonth.count) {
				this.ptr.animate({ height: 180 });
			} else {
				this.ptr.animate({ height: 160 });
			}
		}

		this.aMonths.push(newMonth);
		
		setCurrent(newMonth);

	},
	
	showControls: function(){
		if(!this.is.controlsState){
			this.is.controlsState = true;
			this.ptr.parents("div.calendar").find("div.calendar-controls").css({ height: 0, overflow: "hidden" }).show().
				animate({ height: 40 });
		}
	},
	selectByDay: function(day, evt){

		if(!evt.shiftKey) {
			this.empty(this.current);
		}

		var k;
		jQuery(day).parent().find("li").each(function(i){
			if(day == this) {
				k = i;
			}
		});
		k++;
		if(k == 7) {k = 0;}
		this.current = this.getCurrent();
		for(var key in this.current.items){
			var date = new Date(key);
			if(date.getDay() == k){
				this.current.items[key]._selected = true;
				this.current.items[key].ptr.addClass("selected");
			}
		}
		this.is.controls = true;

		this.redraw(this.current);
		this.onmouseup();
	},
	
	selectByWeek: function(evt){
		var week = this.getWeek(this.current, evt.pageY - this.cy);

		if(!evt.shiftKey) {
			this.empty(this.current);
		}

		for(var key in this.current.items){
			if(this.current.items[key].top == week.top){
				this.current.items[key]._selected = true;
				this.current.items[key].ptr.addClass("selected");
			}
		}

		this.is.controls = true;

		this.redraw(this.current);
		this.onmouseup();
		
	},
	redraw: function(month){
		function check(d){
			return month.items[d.toString()] && month.items[d.toString()].ptr.is('.selected');
		}

		function add(){
			if(arguments.length > 1){
				if(d.getDay() == arguments[0]) {sClass += 'o';}
				else {add(arguments[1]);}
			} else {
				var _d = new Date(d.getFullYear(), d.getMonth(), d.getDate()+arguments[0]);
				if(check(_d)) {sClass += 'f';}
				else {sClass += 'o';}
			}
		}
		
		function removeClasses(day){
			var s = day.ptr.is(".selected");
			day.ptr.attr("class", day.sClass);
			if(s) {day.ptr.addClass("selected");}
		}
		
		for(var k in month.items){
			var curr = month.items[k];
			removeClasses(curr);
			if(curr.ptr.is(".selected")){
				var d = new Date(k);
				
				var sClass = '';
				add(-7);
				add(0, 1);
				add(7);
				add(1,-1);
				add(1,-8);
				
				curr.ptr.addClass(sClass);
				
			}
		}
	},
	empty: function(month){
		this.hSetting.dates = [];
		for (var i=0; i < this.aMonths.length; i++) {
			for(var k in this.aMonths[i].items){
				var curr = this.aMonths[i].items[k];
				curr.selected = curr._selected = false;
				curr.ptr.removeClass("selected");
			}
		}
	},

	getCurrent: function(){
		for (var i=0; i < this.aMonths.length; i++) {
			if(this.aMonths[i].current){
				return this.aMonths[i];
			}
		}
		return this.aMonths[0];
	},
	getDay: function(month, x, y){
		for(var k in month.items){
			if(((x >= month.items[k].left && x < month.items[k].left+20) || (x === null)) && y >= month.items[k].top && y < month.items[k].top+20) {
				return k;
			}
		}
	},
	getWeek: function(month, y){
		var k = this.getDay(month, null, y);
		return k ? month.items[k] : null;
	},

	createMonth: function(oDate){
		var oThis = this;
		function getDate(sDate){
			if(oThis.hSetting.dates) {
				for (var i=0; i < oThis.hSetting.dates.length; i++) {
					if(oThis.hSetting.dates[i] == sDate) {return true;}
				}
			}
			return false;
		}
		
		function events(month){
			month.ptr.find("ul.calendar-week-days li").click(function(evt){
				oThis.selectByDay(this, evt);
			});
			return month;
		}
		
		var now = new Date();
		now = new Date(now.getFullYear(), now.getMonth(), now.getDate());
		var date = new Date(oDate.year, oDate.month-1, 1);
		var next = new Date(oDate.year, oDate.month, 0);
		var month = {
		 	ptr: jQuery("<div class='calendar-month'><div class='calendar-month-in'><h1>" + this.months.first[date.getMonth()] + ((date.getFullYear() != now.getFullYear()) ? (', ' + date.getFullYear()) : '') + "</h1><ul class='calendar-week-days'><li>ПН</li><li>ВТ</li><li>СР</li><li>ЧТ</li><li>ПТ</li><li class='calendar-free'>СБ</li><li class='calendar-free'>ВС</li></ul><ul class='calendar-days'></ul></div></div>"),
			date: new Date(date.getFullYear(), date.getMonth()),
			items: {},
			current: false
		};
		var days = month.ptr.find("ul.calendar-days");

		date.setDate(- (date.getDay() === 0 ? 7 : date.getDay()) + 1);
		
		var diff = next.valueOf() - date.valueOf();
		var to = Math.round(diff/1000/60/60/24 + (7-(next.getDay() === 0 ? 7 : next.getDay())));
		month.count = to;

		for (var i=0; i < to; i++) {
			var sId = '';
			var sClass = '';
			date.setDate(date.getDate()+1);
			if(date.valueOf() == now.valueOf()) {
				sId += " id='calendar-current'";
			}
				
			if(date.valueOf() < now.valueOf()) {
				sClass += " past";
			}
				
			if(date.getMonth() != oDate.month-1){
				sClass += " another";
			}
			
			var day = jQuery("<li" + sId + " class='" + sClass + "'>" + (sId.length ? '<b>' : '') + date.getDate() + (sId.length ? '</b>' : '') + "</li>");
			var sDate = this.dateString(date);
			var bCheck = getDate(sDate);
			if(bCheck) {day.addClass("selected");}
			month.items[date.toString()] = { ptr: day, sClass: sClass, selected: bCheck ? true : false, _selected: bCheck ? true : false };
			days.append(day);
		}
		return events(month);
		
	},
	
	dateString: function(date){
		return ((date.getDate() < 10) ? ('0' + date.getDate()) : date.getDate()) + "-" + (((date.getMonth()+1) < 10) ? ('0' + (date.getMonth()+1)) : (date.getMonth()+1)) + "-" + date.getFullYear();
	}

});

/*global Draggable, jQuery */

var Switcher = classDraggable.extend({
	oninit: function(){

		this.sId = arguments[0];
		
		this.o = {
			ptr: this.ptr,
			root: this.ptr.find("div.switcher"),
			back: this.ptr.find("div.sw-back"),
			knob: this.ptr.find("div.sw-knob")
		};

		if(this.o.root.is(".switcher-left")) {this._state = 1;}
		else {this._state = 0;}
		
		this.state = this._state;

		if(this.o.root.is(".switcher-disabled")) {jQuery.extend(this.is, {
			disabled: true
		});}
		
		this.reinit();
		
		if(this.state) {
		   this._x = this.limits.right;
		}

		this.ptr = this.ptr.find("div.sw-knob div.swk-ctrl");
		
		this.left_value = jQuery(this.o.ptr).find(".swb-l").attr('value') || '0';
		this.right_value = jQuery(this.o.ptr).find(".swb-r").attr('value') || '1';
		if(this.o.root.attr("name")) {
			this.linked_input = jQuery(this.o.ptr).find("input[name=\"" + this.o.root.attr("name") + "\"]");
		}
		if(this.linked_input && this.linked_input.length > 0) {
		  this.state = this._state = (this.linked_input.val() == this.left_value) ? 1 : 0;
		  if(this.state) {
		    this.o.root.addClass("switcher-left");
		    this.correct(this.limits.right);
		  }
		}
	},
	
	reinit: function(){
		jQuery.extend(this.d, {
			backLeft: this.o.back.offset().left,
			rootLeft: this.o.root.offset().left,
			rootWidth: this.o.root.width()
		});

		this.limits = {
			left: -(this.d.rootWidth-34),
			right: 0
		};
		
		this.correct(this.state ? this.limits.right : this.limits.left, false);

//		this.o.back.css({ left: this.d.backLeft-this.d.rootLeft });
//		this.o.knob.css({ left: this.d.backLeft-this.d.rootLeft });

	},
	
	onmousedown: function(){
		if(!this.is.disabled){
			this.reinit();
			jQuery.extend(this.d, {
				backLeft: this.o.back.offset().left
			});
		}
	},
	
	onmousemove: function(evt, x, y){
		if(!this.is.disabled){
			var _x = x-this.d.rootLeft-(this.d.left-this.d.backLeft);
		
			if(_x > this.limits.right) {_x = this.limits.right;}
			if(_x < this.limits.left) {_x = this.limits.left;}
		
			this.o.back.css({ left: _x });
			this.o.knob.css({ left: _x });
		
			this._x = _x;
		}
	},
	
	onmouseup: function(evt){
		if(!this.is.disabled){
			if(this.is.toclick){
				this.onclick.apply(this, [evt]);
			} else {
				this.is.toclick = true;
				if(this._x != this.limits.left || this._x != this.limits.right){
					if(Math.abs(this._x) > Math.round((Math.abs(this.limits.left)-Math.abs(this.limits.right))/2)) {
						this.correct(this.limits.left);
					} else {
						this.correct(this.limits.right);
					}
				}
			}
		}
	},
	
	
	onclick: function(evt){
		switch(this.getState()){
			case 0:
				this.correct(this.limits.right);
				break;
			case 1:
				this.correct(this.limits.left);
				break;
		}
	},
	
	correct: function(x, b){
		this._x = x;
		if(b===false){
  		this.o.back.css({ left: this._x });
  		this.o.knob.css({ left: this._x });
		} else {
  		this.o.back.animate({ left: this._x }, 200);
  		this.o.knob.animate({ left: this._x }, 200);
		}
		var _state = this.getState();
		if(this.state != _state){
			this.state = _state;
			this.handler();
		}
	},
	
	handler: function(){
		if(this.o.root.attr('handler')){
			this.is.disabled = true;
			var _p = this.o.ptr.find("p");
			if(!_p.find("img").length) {
  		  		_p.html("<img src='/images/ajax-loader-white.gif' alt='' />");
  		}
			
  		this.o.root.trigger('switched', [this]);
			eval(this.o.root.attr('handler'));
		}
		
		if(this.o.root.attr('handler_always')){
			eval(this.o.root.attr('handler_always'));
		}
    
    if(this.linked_input) {
  		this.linked_input.val(this.getState() == 1 ? this.left_value : this.right_value);
    }
	},
	
	getState: function(){
		if(this._x == this.limits.left) {
			return 0;
		} else if(this._x == this.limits.right) {
			return 1;
		} else {
			return this._state;
		}	
	}
});


/*global, jQuery, Switcher, current_user_id*/

var oRating = {
	ratingQueue: [],
	append:function(sId){
		sId = '.j-' + sId;
		for(var i=0; i<this.ratingQueue.length; i++){
			if(this.ratingQueue[i].sId == sId){
			  delete this.ratingQueue[i];
			  this.ratingQueue[i] = new Switcher(sId);
				return;
			}
		}
  	this.ratingQueue[this.ratingQueue.length] = new Switcher(sId);
	},
	each: function(callback){
		for (var i=0; i < this.ratingQueue.length; i++) {
			var b = callback.call(this.ratingQueue[i], [i]);
			if(b === false) {break;}
		}
	},
	resources : {}
};

(function(){
oRating.infos = {};
  
oRating.switched = function(switcher_object, info, rating) {
  jQuery.post("/votes", {klass : info.klass, id : info.id, operator : (info.voted ? '-' : '+')}, function(voted) {
    info.voted = voted;
    if(info.voted) {
      info.voters_count++;
    } else {
      info.voters_count--;
    }
    if(info.voters_count < 0) {info.voters_count = 0;}
    switcher_object.is.disabled = false;
    //switcher_object.state = info.voted ? 1 : 0;
    
    var value_html = "" + info.voters_count;
    if(info.friends_count) {
      value_html = value_html + "<span class='friends_count'>"+info.friends_count+"</span>";
    }
    jQuery(rating).find(".value").html(value_html);
  }, "json");  
}

oRating.appendAllRatings = function() {
  setTimeout(function() {
    for(dom_id in oRating.infos) {
      oRating.append(dom_id)
    }
  }, 50);
}

oRating.personalizeRating = function(dom_id) {
  var rating = jQuery(".j-"+dom_id);
  var info = oRating.infos[dom_id];
  var switcher = jQuery(".j-switcher_"+dom_id);
  if(current_user_id) {
    rating.removeClass('disable');
    switcher.removeClass("switcher-disabled");

    switcher.attr('handler', 'true;');
    switcher.bind('switched', function(event, switcher_object) {
      oRating.switched(switcher_object, info, rating)
    });

    if(info.voted) {
      switcher.addClass("switcher-left");
    }
    if(info.friends_count) {
      jQuery(".j-friends_count_"+dom_id).html(''+info.friends_count).show();
    }
  }
  switcher.css('visibility', 'visible');
//  oRating.append(dom_id);
};
})();

jQuery(oRating.appendAllRatings);
(function($){
  this.Highlighter = {
    replacer: function(matchedSubstring, Index, OriginalString){
      return "<i class='search-highlighted'>" + matchedSubstring + "</i>";
    },
    h: function(query, elements_matcher){
      var to_highlight = jQuery(elements_matcher);
      var pattern = new RegExp(query, "gi")
      to_highlight.each(function(i){
        var $this = jQuery(this);
        $this.html($this.html().replace(pattern, Highlighter.replacer));
      });
    }
  }
})( jQuery );
jQuery(document).ready(function(){
	jQuery(".b-mini-look span.event").click(function(){
		var _span = jQuery(this);
		jQuery.post('/admin/mini_looks/' + _span.parents('.b-mini-look').attr('id').replace(/\D+_/, "") + "/change_state.js", {event:_span.attr('event'), _method:'put'}, function(data){
			_span.parents('.b-mini-look').fadeOut('fast');
			jQuery(".b-mini-looks-toolbar").html(data);
		});
	});
});
var _InviteFriends;

function jsSpan(elem){
	this.span = jQuery(elem);
	this.init();
}
jsSpan.prototype = {
	init:function(){
		this.span.hover(function(){
			jQuery(this).css({textDecoration:'underline'});
		}, function(){
			jQuery(this).css({textDecoration:'none'});
		});
	}
};


var jsButton = {};
jsButton.parseIncrement = function(increments_id) {
	var counter_text = jQuery("#" + increments_id).html();
	if(!counter_text) {return null;}
	var counter = counter_text.match(/\d+/);
	if (isNaN(counter)) {
		return null;
	}
	return counter;
};
		
jsButton.writeIncrements = function(increments_id, inc_old, inc) {
	jQuery("#" + increments_id).html(counter_text.replace(inc_old, inc));
};

jsButton.increment = function(button, increments_id) {
  var counter_elem = jQuery("#" + increments_id);
	var counter_text = counter_elem.html();
	if(!counter_text) {return;}
	var counter = parseInt(counter_text.match(/\d+/), 10);
	var new_counter = 0;
	if (isNaN(counter) || counter < 0) {
		return;
	}
	new_counter = button.checked ? counter + 1 : counter - 1;
	
	counter_elem.html(counter_text.replace(counter, new_counter));
};



var preload = ['/images/icon-favorite-act.gif', '/images/icon-favorite-hov.gif', '/images/micro-right-dis.gif', '/images/micro-left-dis.gif', '/images/micro-right-hov.gif', '/images/micro-right-act.gif', '/images/micro-left-hov.gif', '/images/micro-left-act.gif', '/images/users-list-item-act.gif', '/images/users-list-arr-back-act.gif', '/images/users-list-act-bg.gif', '/images/icon-favorite-act.gif', '/images/event-past-slider.png', '/images/event-past-slider-long.png', '/images/icon-star-act.gif', '/images/embed-act-lt.gif', '/images/embed-act-rt.gif', '/images/embed-act-lb.gif', '/images/embed-act-rb.gif', '/images/icon-evt-view2.gif', '/images/icon-evt-view2-act.gif', '/images/icon-evt-view1.gif', '/images/icon-evt-view1-act.gif', '/images/button-act-right.png', '/images/button-act-left.png', '/images/button-act-bg-ie.gif', '/images/button-act-bg.png', '/images/button-hover-right.png', '/images/button-hover-left.png', '/images/button-hover-bg.png', '/images/button-hover-bg-ie.gif', '/images/drop-top-right-bg.gif', '/images/drop-top-right-bg-act.gif', '/images/drop-top-left-bg.gif', '/images/drop-top-left-bg-act.gif', '/images/drop-top-bg.gif', '/images/drop-top-bg-act.gif', '/images/drop-top-arr.gif', '/images/drop-top-arr-dis.gif', '/images/drop-bottom-right-bg.gif', '/images/drop-bottom-right-bg-act.gif', '/images/drop-bottom-left-bg.gif', '/images/drop-bottom-left-bg-act.gif', '/images/drop-bottom-bg.gif', '/images/drop-bottom-bg-act.gif', '/images/drop-bottom-arr.gif', '/images/drop-bottom-arr-dis.gif', '/images/ajax-rating-blue.gif', '/images/ajax-rating-red.gif'];
// эта картинка задрала уже своими 404 '/images/events-new-view.gif', 
// у нас все картинки в /images/, может убрать в функцию? повторение - мать заикания,
// А ТОЧНО! УБЕРУ КАК ГАЛЕРЫ СДЕЛАЮ
// Ну и?

var Preloader = function(aImages){
	var i=0;
	if(aImages.length >0){
		var img = new Image();
		img.src = aImages[0];
		img.onload = function(){
			aImages.shift();
			Preloader(aImages);
		};
	} else {
		return true;
	}
};

function Hairvideo(){
	
}


Hairvideo.prototype = {
  initPlayer:function(){
    var _my = this;
    this.k = 0;
    this.counter = 0;
    this.timeForToggle = 150;
    this.allImgs = jQuery('.flash-outer .photo-player .imgs img');
    this.playPause = jQuery('.flash-outer .photo-player .controls .button');
    this.track = jQuery('.flash-outer .photo-player .controls .slider-wrap');
    this.slider = jQuery('.flash-outer .photo-player .controls .slider-wrap .slider');
    this.allImgs.eq(0).css({visibility:'visible'});
    for(var i=1; i < this.allImgs.length; i++){
      this.allImgs.eq(i).css({visibility:'hidden'});
    }
    this.step = (this.track.width()-this.slider.width())/this.allImgs.length;
    this.timeTemp = this.timeForToggle*this.allImgs.length;
    this.playPause.click(function(){
      _my.togglePlay();
    });
    this.slider.mousedown(function(){
      _my.dragFlag = true;
      _my.startDrag();
    });
    jQuery(window).mousemove(function(evt){
      _my.dragSlider(evt);
    }).mouseup(function(){
      _my.dragFlag = false;
    });
  },
  togglePlay:function(temp){
    var _my = this;
    if(!this.playPause.is('.pause')){
      if(this.counter === 0){
        this.slider.css({left:0});
        this.allImgs.eq(this.allImgs.length-1).css({visibility:'hidden'});
        this.allImgs.eq(0).css({visibility:'visible'});
      }
      this.playPause.addClass('pause');
      this.playPause.css({background:'url(/images/hairlooks/play_act.gif) no-repeat left top'});
      setTimeout(function(){
        _my.playPause.css({background:'url(/images/hairlooks/pause.gif) no-repeat left 1px'});
      }, 150);

      this.slider.animate({left:this.track.width()-this.slider.width()}, this.timeTemp, 'linear');

      this.playerInt = setInterval(function(){
        _my.changePicture();
      }, this.timeForToggle);
    } else {
      this.playPause.removeClass('pause');
      this.playPause.css({background:'url(/images/hairlooks/pause_act.gif) no-repeat left 1px'});
      setTimeout(function(){
        _my.playPause.css({background:'url(/images/hairlooks/play.gif) no-repeat left top'});
      }, 150);
      for(var i=0; i < this.allImgs.length; i++){
        if(this.allImgs.eq(i).css('visibility') == 'visible'){
          this.timeTemp = (this.allImgs.length - this.counter)*this.timeForToggle;
        }
      }
      clearInterval(this.playerInt);
      this.slider.stop();
      this.kickDown = this.counter*this.step;
      this.slider.css({left:this.kickDown});
    }
  },
  changePicture:function(){
    var _my = this;
    for(var i=0; i < this.allImgs.length; i++){
      if(this.allImgs.eq(i).css('visibility') == 'visible'){
        this.counter = i+1;
        this.allImgs.eq(i).css({visibility:'hidden'});
        if(i == this.allImgs.length - 1){
          this.k = 0;
          this.counter = 0;
          this.slider.stop();
          clearInterval(this.playerInt);
          this.playPause.removeClass('pause');
          this.timeTemp = this.timeForToggle*this.allImgs.length;
          this.playPause.css({background:'url(/images/hairlooks/pause_act.gif) no-repeat left 1px'});
          setTimeout(function(){
            _my.playPause.css({background:'url(/images/hairlooks/play.gif) no-repeat left top'});
          }, 150);
          this.allImgs.eq(i).css({visibility:'visible'});
        } else {
          this.k = i + 1;
          this.counter = i+1;
          this.allImgs.eq(this.k).css({visibility:'visible'});
        }
        break;
      }
    }
  },
  startDrag:function(){
    this.tempLeft = this.track.offset().left;
  },
  dragSlider:function(evt){
    var _my = this;
    if(this.dragFlag === true){
      if(evt.pageX >= this.track.offset().left && evt.pageX <= this.track.offset().left + this.track.width()){
        _my.counter = Math.round((evt.pageX - _my.tempLeft)/_my.step);
        _my.slider.css({left:_my.counter*_my.step+_my.tempLeft-_my.track.offset().left});
        for(var i=0; i < this.allImgs.length; i++){
          this.allImgs.eq(i).css({visibility:'hidden'});
        }
        this.allImgs.eq(_my.counter).css({visibility:'visible'});
      }
    }
  }	
};

var Micro = {
	init:function(){
		var _my = this;
		this.aniTime = 500;
		this.micro = jQuery('div.micro');
		this.staticBlock = this.micro.find('div.micro-main');
		this.comments = this.micro.find('div.comments-counter');
		this.commentsLink = this.comments.find('p a');
		this.sayMore = this.staticBlock.find('span.say-more');
		this.items = [];
		this.staticBlock.find('div.item').each(function(i){
			_my.items[i] = {
				ptr:jQuery(this),
				height:jQuery(this).height(),
				comments:jQuery(this).find('.to-comments'),
				link:jQuery(this).find('.to-comments').attr('href'),
				is_now:false
			};
		});
		this.leftArr = this.micro.find('div.left-arr');
		this.rightArr = this.micro.find('div.right-arr');
		this.leftArrDiv = this.leftArr.find('div').css({top:(this.items[0].height+24)/2-15});
		this.rightArrDiv = this.rightArr.find('div').css({top:(this.items[0].height+24)/2-15});
		if(this.items.length == 1){
			this.leftArr.css({visibility:'hidden'});
			this.rightArr.css({visibility:'hidden'});
		}
		this.staticBlock.css({height:this.items[0].height});
		this.posArr(0);
		this.items[0].ptr.css({display:'block'});
		this.items[0].is_now = true;
		if(this.items[0].link){
			this.changeComments(0);
			this.comments.css({display:'block'});
		}
		if(jQuery('#say-intro').length > 0){
			this.comments.css({display:'none'});
		}
		this.leftArrDiv.css({display:'block'});
		this.rightArrDiv.css({display:'block'});
		this.attachEvents();
	},
	posArr:function(elem){
		this.leftArr.height(this.items[elem].height+24);
		this.rightArr.height(this.items[elem].height+24);
		this.leftArrDiv.css({top:(this.items[elem].height+24)/2-15});
		this.rightArrDiv.css({top:(this.items[elem].height+24)/2-15});
	},
	changeComments:function(elem){
		var _my = this;
		if(_my.items[elem].link){
				_my.commentsLink.attr('href', _my.items[elem].link).html(_my.items[elem].comments.html());
		}
	},
	deleteItem:function(id){
		if(jQuery('#'+id).length > 0){
			jQuery('#'+id).remove();
			this.reInit();
		}
	},
	reInit:function(){
		var _my = this;
		jQuery('span.jsSpan').unbind().each(function(){
			var jsspan = new jsSpan(this);
		});
		b_button_init();
		this.items = [];
		this.comments = this.micro.find('div.comments-counter');
		this.commentsLink = this.comments.find('p a');
		this.staticBlock.find('div.item').each(function(i){
			_my.items[i] = {
				ptr:jQuery(this),
				height:jQuery(this).height(),
				comments:jQuery(this).find('.to-comments'),
				link:jQuery(this).find('.to-comments').attr('href'),
				is_now:false
			};
		});
		this.staticBlock.find('div.item .m-favorite').unbind('hover');
		this.staticBlock.find('div.item .m-favorite').hover(function(){
			if(!jQuery(this).is('.m-favorite-act')){
				jQuery(this).css({background:'url(/images/icon-favorite-hov.gif) no-repeat'});
			}
		}, function(){
			if(!jQuery(this).is('.m-favorite-act')){
				jQuery(this).css({background:'url(/images/icon-favorite.gif) no-repeat'});
			}
		});
		if(this.items.length == 1){
			this.leftArr.css({visibility:'hidden'});
			this.rightArr.css({visibility:'hidden'});
		} else {
			this.leftArr.css({visibility:'visible'});
			this.rightArr.css({visibility:'visible'});
		}
	},
	changeHeight:function(id){
		var _my = this;
		var i;
		var now;
		for(i=0; i<this.items.length; i++){
			if(this.items[i].is_now === true){
				this.items[i].ptr.fadeOut('fast');
				break;
			}
		}
		_my.leftArr.addClass('m-dis');
		_my.rightArr.addClass('m-dis');
		this.reInit();
		if(!id){
			id = this.items[0].ptr.attr('id');
		}
		for(i=0; i<this.items.length; i++){
			if(this.items[i].ptr.is('#'+id)){
				now = i;
				this.now = i;
				break;
			}
		}
		this.items[now].is_now = true;
		this.items[now].ptr.removeClass("item-preload").css({ opacity: 1 });
		if(this.items[now].ptr.is('.item-form')){
			this.comments.fadeOut('fast', function(){
				_my.staticBlock.animate({height:_my.items[now].height}, _my.aniTime, 'easeOutQuad', function(){
					_my.items[now].ptr.fadeIn('fast');
				});
			});
		} else {
			this.posArr(now);
			this.staticBlock.animate({height:_my.items[now].height}, _my.aniTime, 'easeOutQuad', function(){
				_my.items[now].ptr.fadeIn('fast', function(){
					if(jQuery('#say-intro').length === 0){
						_my.changeComments(now);
						_my.comments.fadeIn('fast');
					}
				});
				if(now !== 0){
					_my.leftArr.removeClass('m-dis');
				} else {
					_my.leftArr.removeClass('m-hov');
				}
				if(now < _my.items.length-1 && _my.items.length > 1){
					_my.rightArr.removeClass('m-dis');
				} else {
					_my.rightArr.removeClass('m-hov');
				}
			});
		}
	},
	checkNow:function(){
		for(var i=0; i<this.items.length; i++){
			if(this.items[i].is_now === true){
				this.now = i+1;
				break;
			}
		}
	},
	switchMicro:function(dur){
		for(var i=0; i<this.items.length; i++){
			if(this.items[i].is_now === true){
				var now = i;
				break;
			}
		}
		if(dur == -1 && now > 0){
			this.hide(now, dur);
		} else if(dur == 1 && now < this.items.length){
			this.hide(now, dur);
		} else if(dur === 0){
			this.hide(now, dur);
		}
	},
	hide:function(now, dur){
		var _my = this;
		if((dur == -1 && now > 0) || (dur == 1 && now < this.items.length-1)){
			this.leftArr.height(24);
			this.rightArr.height(24);
			this.leftArrDiv.fadeOut('fast');
			this.rightArrDiv.fadeOut('fast');
			this.comments.fadeOut('fast', function(){
				_my.items[now].ptr.fadeOut('fast', function(){
					_my.show(now+dur);
				});
				_my.items[now].is_now = false;
			});
		} else if(dur === 0){
			this.leftArr.height(24);
			this.rightArr.height(24);
			this.leftArrDiv.fadeOut('fast');
			this.rightArrDiv.fadeOut('fast');
			this.comments.fadeOut('fast', function(){
				_my.items[now].ptr.fadeOut('fast', function(){
					_my.show(dur, "hide");
				});
				_my.items[now].is_now = false;
			});
		}
	},
	show:function(now, hide){
		var _my = this;
		if(this.leftArr.is('.m-dis')){
			this.leftArr.removeClass('m-dis');
		}
		if(this.rightArr.is('.m-dis')){
			this.rightArr.removeClass('m-dis');
		}
		if(now == this.items.length-1){
			this.rightArr.addClass('m-dis');
		}
		if(now === 0){
			this.leftArr.addClass('m-dis');
		}
		if(hide){
			this.leftArr.addClass('m-dis');
			this.rightArr.addClass('m-dis');
		}
		if(this.items[now].link){
			this.changeComments(now);
		}
		this.staticBlock.animate({height:this.items[now].height}, this.aniTime, 'easeOutQuad', function(){
			_my.posArr(now);
			_my.items[now].ptr.fadeIn('fast', function(){
				_my.leftArrDiv.fadeIn('fast');
				_my.rightArrDiv.fadeIn('fast');
				_my.items[now].is_now = true;
				if(!_my.items[now].ptr.is('.item-form')){
					_my.comments.fadeIn('fast');
					if(hide){
						_my.rightArr.removeClass('m-dis');
					}
				} else {
					_my.comments.css({display:'none'});
				}
			});
		});
	},
	resize:function(d){
		var delta = Math.abs(d).toString();
		if(d<0){
			this.staticBlock.animate({height:"-="+delta+"px"}, 150, 'easeOutQuad');
		} else {
			this.staticBlock.animate({height:"+="+delta+"px"}, 150, 'easeOutQuad');
		}
	},
	
	preload: function(){
	  var now;
		for(var i=0; i<this.items.length; i++){
			if(this.items[i].is_now === true){
				now = i;
				break;
			}
		}
		
		this.items[now].ptr.addClass("item-preload").animate({ opacity: 0.3 });
		return false;
	},

	attachEvents:function(){
		var _my = this;
		this.leftArr.hover(function(){
			if(!jQuery(this).is('.m-dis')){
				_my.leftArr.addClass('m-hov');
			}
		}, function(){
			if(!jQuery(this).is('.m-dis')){
				_my.leftArr.removeClass('m-hov');
			}
		}).click(function(){
			if(!jQuery(this).is('.m-dis')){
				_my.leftArr.addClass('m-act');
				setTimeout(function(){
					_my.leftArr.removeClass('m-act');
				}, 150);
				_my.switchMicro(-1);
			}
		});
		this.rightArr.hover(function(){
			if(!jQuery(this).is('.m-dis')){
				_my.rightArr.addClass('m-hov');
			}
		}, function(){
			if(!jQuery(this).is('.m-dis')){
				_my.rightArr.removeClass('m-hov');
			}
		}).click(function(){
			if(!jQuery(this).is('.m-dis')){
				_my.rightArr.addClass('m-act');
				setTimeout(function(){
					_my.rightArr.removeClass('m-act');
				}, 150);
				_my.switchMicro(1);
			}
		});
		this.staticBlock.find('div.item .m-favorite').hover(function(){
			if(!jQuery(this).is('.m-favorite-act')){
				jQuery(this).css({background:'url(/images/icon-favorite-hov.gif) no-repeat'});
			}
		}, function(){
			if(!jQuery(this).is('.m-favorite-act')){
				jQuery(this).css({background:'url(/images/icon-favorite.gif) no-repeat'});
			}
		});
	}
};

function CodeForBlog(){
	this.init();
}

CodeForBlog.prototype = {
	init:function(){
		this.spans = jQuery('span.codeForBlog');
		this.spans.hover(function(){
			jQuery(this).css({borderBottom:0});
		}, function(){
			jQuery(this).css({borderBottom:'1px dashed #777'});
		});
	}
};

function PlaceHolders(){
	this.init();
}

PlaceHolders.prototype = {
	init:function(){
		var _my = this;
		if(jQuery.browser.safari){
			jQuery('div.search').removeClass('all-browsers');
		}
	}
};

function AddToBlog(){
	this.init();
}

AddToBlog.prototype = {
	init:function(){
		var _my = this;
		this.inputs = jQuery('input.addToBlog');
		this.inputs.click(function(){
			jQuery(this).select();
		});
	}
};

function Places(){
	
}

Places.prototype = {
	init:function(){
		var _my = this;
		this.places = jQuery('div.places');
		this.staticBlock = this.places.find('div.static');
		this.movedBlock = this.staticBlock.find('ul.moved');
		this.movedBlockHeight = this.movedBlock.height();
		this.staticBlockHeight = (this.movedBlock.find('li').eq(0).height()+1)*this.staticBlock.attr('num')-1;
		this.staticBlock.height(this.staticBlockHeight);
		this.topArr = this.places.find('div.top');
		this.topArr.addClass('t-act');
		this.bottomArr = this.places.find('div.bottom');
		this.slowSpeed = 7;
		this.fastSpeed = 12;
		this.intTime = 30;
		this.deltaHeight = this.staticBlockHeight - this.movedBlockHeight;
		this.bottomArrWrap = this.bottomArr.find('div.wrapper');
		this.bottomArrBlock = this.bottomArr.find('div.grey-block');
		this.topArrWrap = this.topArr.find('div.wrapper');
		this.topArrBlock = this.topArr.find('div.grey-block');
		this.topLeft = this.topArr.find('img.left');
		this.topRight = this.topArr.find('img.right');
		this.bottomLeft = this.bottomArr.find('img.left');
		this.bottomRight = this.bottomArr.find('img.right');
		this.bottomArr.hover(function(){
			_my.aniScroll(_my.slowSpeed, -1);
		}, function(){
			_my.aniScroll(0, 0);
		}).mousedown(function(){
			_my.aniScroll(_my.fastSpeed, -1);
		}).mouseup(function(){
			_my.aniScroll(_my.slowSpeed, -1);
		});
		this.topArr.hover(function(){
			_my.aniScroll(_my.slowSpeed, 1);
		}, function(){
			_my.aniScroll(0, 0);
		}).mousedown(function(){
			_my.aniScroll(_my.fastSpeed, 1);
		}).mouseup(function(){
			_my.aniScroll(_my.slowSpeed, 1);
		});
	},
	aniScroll:function(speed, dir){
		var _my = this;
		if(dir == -1){
			_my.bottomArrWrap.css({backgroundColor:'#cacaca'});
			_my.bottomArrBlock.css({backgroundColor:'#cacaca'});
			_my.bottomLeft.attr('src', '/images/embed-act-lb.gif');
			_my.bottomRight.attr('src', '/images/embed-act-rb.gif');
			_my.topLeft.attr('src', '/images/embed-lt.gif');
			_my.topRight.attr('src', '/images/embed-rt.gif');
			_my.topArr.removeClass('t-act');
		} else if(dir == 1){
			_my.topArrWrap.css({backgroundColor:'#cacaca'});
			_my.topArrBlock.css({backgroundColor:'#cacaca'});
			_my.topLeft.attr('src', '/images/embed-act-lt.gif');
			_my.topRight.attr('src', '/images/embed-act-rt.gif');
			_my.bottomLeft.attr('src', '/images/embed-lb.gif');
			_my.bottomRight.attr('src', '/images/embed-rb.gif');
			_my.bottomArr.removeClass('b-act');
		} else {
			_my.topArrWrap.css({backgroundColor:'#eaeaea'});
			_my.bottomArrWrap.css({backgroundColor:'#eaeaea'});
			_my.topArrBlock.css({backgroundColor:'#eaeaea'});
			_my.bottomArrBlock.css({backgroundColor:'#eaeaea'});
			_my.topLeft.attr('src', '/images/embed-lt.gif');
			_my.topRight.attr('src', '/images/embed-rt.gif');
			_my.bottomLeft.attr('src', '/images/embed-lb.gif');
			_my.bottomRight.attr('src', '/images/embed-rb.gif');
		}
		clearInterval(this.aniInt);
		if(dir !== 0){
			this.aniInt = setInterval(function(){
				var tempTop = parseInt(_my.movedBlock.css('top'), 10);
				if(tempTop <=0 && tempTop >= _my.deltaHeight){
					if(tempTop+speed*dir <= 0 && tempTop+speed*dir >= _my.deltaHeight){
						_my.movedBlock.css({top:tempTop+speed*dir});
					} else if(tempTop+speed*dir < 0 + speed*dir && dir == 1){
						clearInterval(_my.aniInt);
						_my.movedBlock.css({top:0});
						_my.topArr.addClass('t-act');
					} else if(tempTop+speed*dir > _my.deltaHeight+speed*dir && dir == -1){
						clearInterval(_my.aniInt);
						_my.movedBlock.css({top:_my.deltaHeight+1});
						_my.bottomArr.addClass('b-act');
					}
				}
			}, this.intTime);
		}
	}
};






function evtItem(sId){ this.sId = sId; }
evtItem.prototype = {
	init:function(){
		this.is = {
			flag: false,
			clickFlag: true,
			noClick: true,
			on: false
		};
		this.ptr = jQuery("#" + this.sId);
		this.data = {
			parent: this.ptr.find('div.rating'),
			h4: this.ptr.find('h4'),
			date: ""
		};
		this.data.date = this.data.h4.text().match(/(\d+) (.*)/)[0];
		this.data.wrap = this.data.parent.find('div.wrap');
	}
};

function addBlock(obj){
	this.span = jQuery(obj);
	this.init();
}

addBlock.prototype = {
	init:function(){
		var _my = this;
		this.name = this.span.attr('name');
		this.cloned = jQuery('#'+_my.name).clone().removeClass('no-top-pad no-border').removeAttr('id');
		this.blocks = jQuery('div.'+this.cloned.attr('class'));
		for(var i=0; i<this.blocks.length; i++){
			if(this.blocks.eq(i).attr('id') == this.name){
				this.firstI = i-1;
				break;
			}
		}
		this.blocks.eq(this.firstI+1).find('input.hideBlock').get(0).checked = false;
		this.blocks.eq(this.firstI+1).find('input.hideBlock').click(function(){
			_my.toggleChecks(this);
		});
		this.span.hover(function(){
			jQuery(this).css({borderBottom:0});
		}, function(){
			jQuery(this).css({borderBottom:'1px dashed #777'});
		}).click(function(){
			_my.cloneBlock();
		});
	},
	attachChecks:function(){
		var _my = this;
		this.blocks = jQuery('div.'+this.cloned.attr('class'));
		this.checks = this.blocks.eq(this.firstI+1).find('input.hideBlock');
		this.checks.click(function(){
			_my.toggleChecks(this);
		});
	},
	toggleChecks:function(elem){
		this.elem = jQuery(elem);
		this.parent = this.elem.parents('div.'+this.cloned.attr('class'));
		this.blockToHide = this.parent.find('div.hideBlock');
		if(this.elem.get(0).checked){
			this.blockToHide.fadeOut('fast');
		} else {
			this.blockToHide.fadeIn('fast');
		}
	},
	cloneBlock:function(){
		var _my = this;
		this.firstI = this.firstI + 1;
		this.blocks = jQuery('div.'+this.cloned.attr('class'));
		this.cloned.clone().css({display:'none'}).insertAfter(this.blocks.eq(this.firstI)).show('normal');
		this.attachChecks();
	}
};

function UsersAdd(obj){
	this.parent = jQuery(obj);
	this.init();
}

UsersAdd.prototype = {
	init:function(){
		var _my = this;
		this.left = this.parent.find('div.left-list');
		this.right = this.parent.find('div.right-list');
		this.items = this.parent.find('div.item-wrap');
		this.countFlag = false;
		if(this.parent.find('.l-right span').length > 0){
			this.counterBlock = this.parent.find('.l-right span');
			this.count = jQuery('div.item-wrap', this.right).length;
			this.counterBlock.html(this.count+' из 28');
			this.error = jQuery('div.users-list-info div.error');
			this.countFlag = true;
		}
		
		this.flag = true;
		this.items.click(function(){
			_my.checkMax(this);
		});
		if(jQuery('#r-random').length > 0 && jQuery('#r-random').length > 0){
			this.favor = jQuery('#r-favor');
			this.random = jQuery('#r-random');
			this.favor.click(function(){
				_my.radioBut();
			});
			this.random.click(function(){
				_my.radioBut();
			});
			this.radioBut();
		}
	},
	checkMax:function(obj){
		var _my = this;
		if(this.countFlag === true){
			if(jQuery(obj).parent().attr('class') == this.left.attr('class')){
				this.count = jQuery('div.item-wrap', this.right).length;
				if(this.count +1 <= 28){
					_my.checkPos(obj);
				} else {
					_my.error.show('fast');
					_my.left.css({backgroundColor:'red'});
					_my.right.css({backgroundColor:'red'});
					_my.left.animate({backgroundColor:'white'}, 200);
					_my.right.animate({backgroundColor:'white'}, 200);
				}
			} else {
				_my.error.hide('fast');
				_my.checkPos(obj);
			}
		} else {
			this.checkPos(obj);
		}
	},
	countFunc:function(){
		if(this.countFlag === true){
			this.count = jQuery('div.item-wrap', this.right).length;
			this.counterBlock.html(this.count+' из 28');
		}
	},
	sortFunc:function(a, b){
		return parseInt(a.split('_')[1], 10)-parseInt(b.split('_')[1], 10);
	},
	radioBut:function(){
		var _my = this;
		if(_my.favor.get(0).checked === true){
			jQuery('div.users-list-freeze').css({display:'none'});
			jQuery('input', _my.right).each(function(){
				jQuery(this).get(0).disabled = false;
			});
		}
		if(_my.random.get(0).checked === true){
			jQuery('div.users-list-freeze').css({display:'block'});
			jQuery('input', _my.right).each(function(){
				jQuery(this).get(0).disabled = true;
			});
		}
	},
	checkPos:function(obj){
		var _my = this;
		if(this.flag === true){
			this.flag = false;
			this.leftArray = [];
			this.rightArray = [];
			jQuery('div.item-wrap', this.left).each(function(){
				var lId = jQuery(this).attr('id');
				_my.leftArray.push(lId);
			});
			jQuery('div.item-wrap', this.right).each(function(){
				var rId = jQuery(this).attr('id');
				_my.rightArray.push(rId);
			});
			this.elem = jQuery(obj);
			this.id = this.elem.attr('id');
			if(this.elem.parent().attr('class') == this.left.attr('class')){
				this.rightArray.push(this.id);
				this.elem.addClass('active');
				this.elem.find('input').get(0).disabled = false;
				this.temp = this.elem.clone();
				this.temp.css({display:'none'});
				setTimeout(function(){
					if(jQuery('div.item-wrap', _my.right).length === 0){
						if(jQuery.browser.msie){
							_my.elem.remove();
							_my.right.html(_my.temp);
							_my.temp.css({display:'block'});
							setTimeout(function(){
								_my.temp.removeClass('active');
								_my.flag = true;
								_my.countFunc();
							}, 250);
						} else {
							_my.elem.hide('fast', function(){
								_my.elem.remove();
							});
							_my.right.html(_my.temp);
							_my.temp.show('fast', function(){
								setTimeout(function(){
									_my.temp.removeClass('active');
									_my.flag = true;
									_my.countFunc();
								}, 150);
							});
						}
					} else {
						_my.rightArray.sort(_my.sortFunc);
						for(var i=0; i<_my.rightArray.length; i++){
							if(_my.id == _my.rightArray[i]){
								if(jQuery.browser.msie){
									_my.elem.remove();
									if(jQuery('div.item-wrap', _my.right).eq(i).html() !== null){
										_my.temp.insertBefore(jQuery('div.item-wrap', _my.right).eq(i));
									} else {
										_my.temp.insertAfter(jQuery('div.item-wrap', _my.right).eq(i-1));
									}
									_my.temp.css({display:'block'});
									setTimeout(function(){
										_my.temp.removeClass('active');
										_my.flag = true;
										_my.countFunc();
									}, 250);
									break;
								} else {
									_my.elem.hide('fast', function(){
										_my.elem.remove();
									});
									if(jQuery('div.item-wrap', _my.right).eq(i).html() !== null){
										_my.temp.insertBefore(jQuery('div.item-wrap', _my.right).eq(i));
									} else {
										_my.temp.insertAfter(jQuery('div.item-wrap', _my.right).eq(i-1));
									}
									_my.temp.show('fast', function(){
										setTimeout(function(){
											_my.temp.removeClass('active');
											_my.flag = true;
											_my.countFunc();
										}, 150);
									});
									break;
								}
							}
						}
					}
				}, 150);
				
				this.temp.click(function(){
					_my.checkMax(this);
				});
			} else {
				this.leftArray.push(this.id);
				this.elem.addClass('active');
				this.elem.find('input').get(0).disabled = true;
				this.temp = this.elem.clone();
				this.temp.css({display:'none'});
				setTimeout(function(){
					if(jQuery('div.item-wrap', _my.left).length === 0){
						if(jQuery.browser.msie){
							_my.elem.remove();
							_my.left.html(_my.temp);
							_my.temp.css({display:'block'});
							setTimeout(function(){
								_my.temp.removeClass('active');
								_my.flag = true;
								_my.countFunc();
							}, 250);
						} else {
							_my.elem.hide('fast', function(){
								_my.elem.remove();
							});
							_my.left.html(_my.temp);
							_my.temp.show('fast', function(){
								setTimeout(function(){
									_my.temp.removeClass('active');
									_my.flag = true;
									_my.countFunc();
								}, 150);
							});
						}
					} else {
						_my.leftArray.sort(_my.sortFunc);
						for(var i=0; i<_my.leftArray.length; i++){
							if(_my.id == _my.leftArray[i]){
								if(jQuery.browser.msie){
									_my.elem.remove();
									if(jQuery('div.item-wrap', _my.left).eq(i).html() !== null){
										_my.temp.insertBefore(jQuery('div.item-wrap', _my.left).eq(i));
									} else {
										_my.temp.insertAfter(jQuery('div.item-wrap', _my.left).eq(i-1));
									}
									_my.temp.css({display:'block'});
									setTimeout(function(){
										_my.temp.removeClass('active');
										_my.flag = true;
										_my.countFunc();
									}, 250);
									break;
								} else {
									_my.elem.hide('fast', function(){
										_my.elem.remove();
									});
									if(jQuery('div.item-wrap', _my.left).eq(i).html() !== null){
										_my.temp.insertBefore(jQuery('div.item-wrap', _my.left).eq(i));
									} else {
										_my.temp.insertAfter(jQuery('div.item-wrap', _my.left).eq(i-1));
									}
									_my.temp.show('fast', function(){
										setTimeout(function(){
											_my.temp.removeClass('active');
											_my.flag = true;
											_my.countFunc();
										}, 150);
									});
									break;
								}
							}
						}
					}
				}, 150);
				this.temp.click(function(){
					_my.checkMax(this);
				});
			}
		}
	}
};

function auto_complete_update_element_callback(element, value) {
 $A(value.getElementsByTagName('span')).each(function(element) {
   var classNames = element.className.split(' ');
   if(classNames.length == 1 && $(element.className)) {
     $(element.className).value = element.innerHTML;
   }
 });
}

var Flash = {
	// надо для поддержки старого флеша
	new_swfobject: function(url, width, height) {
		swfobject.embedSWF(url, url, width, height, "9.0.0");
	},
	super_new_swfobject: function(url, id, width, height) {
		swfobject.embedSWF(url, id, width, height, "9.0.0");
	}
};


function colorize_error_checkbockses(){
	jQuery("input[type=checkbox].invalid").each(function(){
		var error_text = jQuery(this).attr("error_text"); 
		var checkbox_text = jQuery("label[for=" + this.id + "]");
		checkbox_text.css({"background-color": "#FFC7C7"});
		checkbox_text.html(checkbox_text.html() + "<div class='error-message'>" + error_text + "</div>");
	});
}

// Cчиталка-ограничитель
InputCounter = _Class.extend({
	init: function(elem) {
		this.inputElement = jQuery(elem);
		this.maxlength = parseInt(this.inputElement.attr("maxlength"), 10);
		if (isNaN(this.maxlength) || this.maxlength <= 0 || this.maxlength >= 100000) {
			return;
		}
		this.counter = jQuery(document.createElement('div'));
		this.counter.addClass('input-counter');
		this.counter.html(this.maxlength - this.inputElement.get(0).value.length);
		this.inputElement.after(this.counter);
		var _my = this;
		this.inputElement.keyup(function(){
			_my.counter.html(_my.maxlength - _my.inputElement.get(0).value.length);
		});
	}
});

// Карта для мест
PlaceMap = _Class.extend({
  init: function(map_id, lat, lng){
    this.pmap = new google.maps.Map2(document.getElementById(map_id));
    this.pmap.addControl(new GLargeMapControl());
    this.pmap.addControl(new GMapTypeControl());
    this.pmap.enableScrollWheelZoom()
    this.pmap.setCenter(new GLatLng(lat, lng), 15);
	  this.place_mark = false;
  },
  handle_inputs: function(){
  	jQuery("#" + this.inputs_prefix + '_lat').attr('value', this.place_mark.getLatLng().lat());
    jQuery("#" + this.inputs_prefix + '_lng').attr('value', this.place_mark.getLatLng().lng());
  },
  geocode_address: function(text){
    var geocoder = new GClientGeocoder();
    var _me = this;
    geocoder.getLocations(text, function(response){
      if (!response || response.Status.code != 200) {alert("Ничего не найдено")}
      else{
        var place = response.Placemark[0];
        var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
        _me.pmap.setCenter(point);
        _me.move_place_marker(point);
      }
    });
  },
  move_place_marker: function(latlng){
    this.place_mark.setLatLng(latlng);
    this.handle_inputs();
  },
  set_place_marker: function(lat, lng, text, handle_inputs_prefix){
    if(!!this.place_mark){this.pmap.removeOverlay(this.place_mark);}
    this.place_text = text;
    this.point = new GLatLng(lat, lng);

    this.pmap.setCenter(this.point, 16);
    this.place_mark = new GMarker(this.point, {draggable: !!handle_inputs_prefix});
   

    // Если карта предназначена для редактирования, а не просмотра, обновляем 
    // values у инпутов с именами _lat, _lng с префиксом handle_inputs_prefix
    if (!!handle_inputs_prefix){
      this.inputs_prefix = handle_inputs_prefix;
      this.pmap.addOverlay(this.place_mark);
      this.handle_inputs();
      var _me = this;
      GEvent.addListener(this.place_mark, "dragend", function() {
        _me.handle_inputs();});
    } else {
      this.pmap.addOverlay(this.place_mark);
      this.pmap.openInfoWindowHtml(this.point, "<p class='bubble-mapbubble'>" + this.place_text + "</p>");
    }
  }
});

BubblePlaceMap = {
  load_for_bubble : function(lat, lng, title){
    google.load('maps', '2.x', {'callback' : function(){
      window.GMAPS_LOADED = true;
        BubblePlaceMap.render_bubble_map(lat, lng, title);
      }
    });
  },
  render_bubble_map: function(lat, lng, title){
    if (window.GMAPS_LOADED && window.BUBBLE_LOADED && !BubblePlaceMap.rendered){
      place_map = new PlaceMap("PlaceMapID", lat, lng);
      place_map.set_place_marker(lat, lng, title, false);
      BubblePlaceMap.rendered = true;
      setTimeout("place_map.pmap.checkResize()", 300);
    }
  }
}


function Friend(user){
	this.init(user);
}

Friend.prototype = {
	init:function(user){
		var _my = this;
		this.bool = false;
		this.user = user;
		this.checkBlock = this.user.find('div.checkbox');
		this.check = this.user.find('input');
		this.check.removeAttr('checked');
		this.user.click(function(){
			_my.moveUser();
		});
	},
	moveUser:function(){
		var _my = this;
		this.check.attr('checked', 'checked');
		this.user.removeClass('visible');
		var id = this.user.attr('id');
		for(var i=0; i<_InviteFriends.usersHash.length; i++){
			if(_InviteFriends.usersHash[i].id == id){
				_InviteFriends.usersHash[i].on_left = false;
				break;
			}
		}
		this.copied = this.user.clone();
		this.copied.attr('id', this.copied.attr('id')+'_copy');
		selectedUsers.append(_my.copied.removeClass('hover')).addClass('selected-block');
		jQuery("#EmptyBlock").removeClass('empty-block');
		this.initSelected(this.copied);
	},
	initSelected:function(item){
		var _my = this;
		item.click(function(){
			var id = item.attr('id').replace('_copy', '');
			item.remove();
			jQuery("#"+id).addClass('visible');
			jQuery("#"+id+"_check").removeAttr("checked");
			for(var i=0; i<_InviteFriends.usersHash.length; i++){
				if(_InviteFriends.usersHash[i].id == id){
					_InviteFriends.usersHash[i].on_left = true;
					break;
				}
			}
			if(selectedUsers.find('div.item').length == 0){
				jQuery("#EmptyBlock").addClass('empty-block');
				selectedUsers.removeClass('selected-block');
			}
		});
	}
}

function InviteFriends(){
	this.init();
}

InviteFriends.prototype = {
	init:function(){
		var _my = this;
		selectedUsers = jQuery('#SelectedUsers');
		allUsers = jQuery('#AllUsers');
		this.usersHash = [];
		allUsers.find('div.item').each(function(){
			var user = jQuery(this);
			var id = user.attr('id');
			_my.usersHash.push({'id': id, "name":user.find('#'+id+'_nick').text()+user.find('#'+id+'_name').text(), on_left:true});
			new Friend(user);
		});
    if(window.location.hash == "#list_already_invited"){
      this.scrollToInvited();
    }
	},
	incremental:function(obj){
		var pattern = new RegExp(".*"+obj.value+".*", "i");
		for(var i=0; i< this.usersHash.length; i++){
			if(this.usersHash[i].name.match(pattern) && this.usersHash[i].on_left){
				jQuery('#'+this.usersHash[i].id).addClass('visible');
			} else {
				jQuery('#'+this.usersHash[i].id).removeClass('visible');
			}
		}
	},
	scrollToInvited:function(){
		this.invited = jQuery('#already_invited');
		allUsers.parent().scrollTo(this.invited, 500);
	}
}


function Lam(){}
Lam.prototype = {
	init:function(){
		var _my = this;
		
		if(jQuery('div.search').length > 0){
			var ph = new PlaceHolders();
		}
		
		jQuery('div.users-list').each(function(){
			var ua = new UsersAdd(jQuery(this));
		});
		
		
//		if(jQuery('div.drop-menu').length > 0){
//       		var cities = new Cities();
//      		cities.init();
//		}
		if(jQuery('span.codeForBlog').length > 0){
       		var cfb = new CodeForBlog();
		}

		jQuery('span.jsSpan').each(function(){
	 		var js = new jsSpan(this);
		});

		jQuery('span.addBlock').each(function(){
       		var ab = new addBlock(jQuery(this));
		});

		if(jQuery('div.rating-inner').length !=0){
			this.getRatingInnerWidth();
			
			jQuery('div.rating-inner .minus').hover(function(){
				jQuery(this).addClass('minus-hover');
			}, function(){
				jQuery(this).removeClass('minus-hover');
			});
			
			jQuery('div.rating-inner .plus').hover(function(){
				jQuery(this).addClass('plus-hover');
			}, function(){
				jQuery(this).removeClass('plus-hover');
			});
		}

		if(jQuery('div.places').length > 0){
			var places = new Places();
			places.init();
		}
		
		jQuery('tr.external-user span.remove').each(function(){
			var jthis = jQuery(this);
			new SpanButton(jthis);
			jthis.click(function(){
				container = jthis.parents('tr.external-user');
				jthis.unbind();
				jQuery.ajax({
					type: "POST",
					url: "/external_users/" + container.attr('id').replace(/\D*/, ''),
					data: "_method=DELETE",
					success: function(data) {
						container.fadeOut('fast');
					}
			 	});
			});
		});
		
		if(jQuery('input.addToBlog').length > 0){
			var atb = new AddToBlog();
		}
		return this;
	},
	getRatingInnerWidth:function(){
		k = jQuery('div.rating-inner .points .value span').html().length
		if ( jQuery('div.rating-inner .minus').length > 0 ) {
			k = (k>1) ? (k-2)*30 : (k-1)*30
			k = '-' + k
			jQuery('div.rating-inner').css('left', eval(340+ k) +'px');
		} else {
			k = (k)*30
			k = '-' + k
			jQuery('div.rating-inner').css('left', eval(370+ k) +'px');
		}
	}
};

function SpanButton(elem){
	this.init(elem);
}

SpanButton.prototype = {
	init:function(elem){
		elem.hover(function(){
			elem.addClass('hover').parent().addClass('active');
		}, function(){
			elem.removeClass('hover').parent().removeClass('active');
		});
	}
}


function ExternalUser(){}
ExternalUser.prototype = {
	init:function(){
		var _my = this;
		jQuery("#external-users div.external-user").each(function(){
			_my.init_external_user(jQuery(this));
		})
	}, 
	init_external_user:function(block){
		var _my = this;
		new SpanButton(block.find("span.remove"));
		new SpanButton(block.find("span.add"));
		block.find("span.add").click(function(){
			jQuery.ajax({
				type: "POST",
				url: "/friendship",
				data: "id=" + block.find("li.add input[type=hidden]").val(),
				success: function() {
					jQuery.ajax({
						type: "POST",
						url: "/external_users/next",
						success: function(data) {
							_my.remover(block, data);
						}
					});
				}
			});
		});
		block.find("span.remove").click(function(){
			jQuery(this).unbind();
			jQuery.ajax({
				type: "POST",
				url: "/external_users/" + block.attr('id').replace(/\D*/, ''),
				data: "_method=DELETE&vomit=true",
				// может вернуться либо код нового юзера, на который надо навесить событие
				// либо пустая строка (больше пользователей нет)
				success: function(data) {
					_my.remover(block, data);
				}
		 	});
		});
	},
	remover:function(block, data) {
		var _my = this;
		block.fadeOut('fast', function(){
			if (data) {
				block.after(data);
				_my.init_external_user(jQuery("#" + data.match(/external_user_\d+/)));
			}
			block.remove();
			// если включенных блоков .external_user 0, то тогда убрать блок #external-users
			if (jQuery("#external-users div.external-user").length == 0){
				jQuery("#external-users").toggle();
			}
		});
	}
};


function poptastic(url){
	var newwindow;
	newwindow = window.open(url,'name','height=400,width=200');
	if (window.focus) {newwindow.focus()}
}


jQuery(document).ready(function(){
  /* js logout */
  jQuery("#logout_button").click(function(){
    jQuery.cookie('auth_token', null);
    jQuery.cookie('auth_token', null, {domain : ".lookatme.ru"});
    jQuery.cookie('auth_token', null, {domain : "www.lookatme.ru"});
    jQuery.cookie('lam', null);
    jQuery.cookie('lam', null, {domain : ".lookatme.ru"});
    jQuery.cookie('lam', null, {domain : "www.lookatme.ru"});
  });

  if(false){
		var godness = (parseInt(jQuery.cookie('higgs_boson')) || 0) + 1;
		jQuery.cookie('higgs_boson', godness);
		alert(godness);
		if(godness == 5){ poptastic('http://www.lookatme.ru/specials/ford-fiesta/');alert(godness); }
  }

	var lam = new Lam();
	lam.init();
	if(jQuery('div.bubble').length > 0){
		Bubble.init();
		jQuery(window).resize(function(){
			Bubble.checkWindowParam();
		});
	}
	if(jQuery('div.micro').length > 0){
		Micro.init();
	}
	
	if(jQuery('div.invite-friends div.left-part-wrap').length !=0){
		_InviteFriends = new InviteFriends();
	}

	if(jQuery('.flash-outer .photo-player').length > 0){
	var hair = new Hairvideo();
	  setTimeout(function(){
	    hair.initPlayer();
	  }, 500);
	}

	jQuery(".input-wrapper").each(function(iw){
	  new InputCounter(jQuery(iw).children().get(0));
	});

	//Preloader(preload);
 	colorize_error_checkbockses();

	var external_user = new ExternalUser();
	external_user.init();
});

(function($) {

  $(document).ready(function(){
    GLOBAL.reInit(function(){
      $(".bb-forms input[type=text], .bb-forms input[type=password], .bb-forms textarea")
        .focus(function(){
          var parent = $(this).parents(".field");
          if(parent.length)
            parent.eq(parent.length-1).addDependClass("focused");
        })
        .blur(function(){
          var parent = $(this).parents(".field");
          if(parent.length)
            parent.eq(parent.length-1).removeDependClass("focused");
        })
        .each(function(){

          function check(){
            if( input.val().length > 0 ){
              form.addDependClass("clear")
            } else {
              form.removeDependClass("clear");
            }
          }

          var input = $(this);
          var form = input.parents(".bb-forms-string");
          if( input.attr("eraseable") == "true" && form.find(".bb-forms-input-clear").length == 0 ){
            var fields = form.find(".field");
            var field = fields.eq(fields.length-1);

            input.keyup(check).change(check).focus(check).blur(check);
            check();

            $("<div>")
              .addClass("bb-forms-input-clear")
              .mousedown(function(){
                input.focus().select();
                return false;
              })
              .click(function(){
                input.val("").focus().change().keyup();
              })
              .appendTo(field);

          }
        })
        
      $(".bb-forms-sample")
        .click(function(){
          var self = $(this);
          if( self.parents(".bb-forms").length ){
            $(this)
              .parents(".bb-forms-string")
                .find("input[type=text], textarea")
                .focus()
                .val($(this).text())
                .change();
          } else {
            var uid = self.attr("class").match(/bb-forms-sample-([^ ]+)/i);
            if(uid && uid[1]){
              $("#" + uid[1])
                .focus()
                .val(self.attr("title").trim())
                .change();
            }
          }
          return false;
        })

      $(".j-focus-onload")
        .removeClass("j-focus-onload")
        .focus();

    });
  })

})(jQuery);
