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

function totimer(js_var_name, id_div, start_sec, sec_end, fl_h, callback) {

  this.timerID = null;
  this.id_div = id_div;
  this.start_sec = start_sec;
  this.sec_end = sec_end; // 0 - minus, >0 - end, -1 +бесконечность  
	this.fl_h = fl_h;
	this.js_var_name = js_var_name;
	if (!callback) {this.callback = null;} else {this.callback = callback;}
	this.fl_stop=true;
	
	this.stop = function() {
               clearTimeout(this.timerID);
		this.fl_stop=true;
	}
	
	this.start = function() {
	   this.fl_stop=false;
           this.displayTime();
	}
	
	this.setSec = function(s, stop) {
           if (!stop) {stop=false;}
  	   this.fl_stop=stop;
           clearTimeout(this.timerID);
  	   this.start_sec=s;
	   this.displayTime();
	}
	
  this.displayTime = function() {
		if (this.start_sec>=0) {
			s=this.start_sec % 60;
			m=Math.floor(this.start_sec/60);
			if (this.fl_h) {
				h=Math.floor(m/60);
				m=m % 60;
				h = h<10 ? h='0'+h+':' : h+':';
			} else {
			  h='';
			}
			m = m<10 ? m='0'+m+':' : m+':';
			s = s<10 ? s='0'+s : s;
//_debug(this.id_div+' '+h+m+s);
			$(this.id_div).html(h+m+s);
			if ((this.start_sec>0 && this.sec_end==0) || this.sec_end==-1 || (this.sec_end>0 && this.start_sec<this.sec_end)) {
				if (this.sec_end==0) {this.start_sec--;} else {this.start_sec++;}
			 if (!this.fl_stop) {this.timerID = setTimeout(this.js_var_name+'.displayTime()',1000);}
		  } else {
				this.stop();
				if (this.callback) this.callback();
		  }	
    }
  }
}

/*
 * Metadata - jQuery plugin for parsing metadata from elements
 *
 * Copyright (c) 2006 John Resig, Yehuda Katz, JяПНУЖrn Zaefferer, Paul McLanahan
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 *
 */

/**
 * Sets the type of metadata to use. Metadata is encoded in JSON, and each property
 * in the JSON will become a property of the element itself.
 *
 * There are three supported types of metadata storage:
 *
 *   attr:  Inside an attribute. The name parameter indicates *which* attribute.
 *          
 *   class: Inside the class attribute, wrapped in curly braces: { }
 *   
 *   elem:  Inside a child element (e.g. a script tag). The
 *          name parameter indicates *which* element.
 *          
 * The metadata for an element is loaded the first time the element is accessed via jQuery.
 *
 * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
 * matched by expr, then redefine the metadata type and run another $(expr) for other elements.
 * 
 * @name $.metadata.setType
 *
 * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("class")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from the class attribute
 * 
 * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("attr", "data")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a "data" attribute
 * 
 * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
 * @before $.metadata.setType("elem", "script")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a nested script element
 * 
 * @param String type The encoding type
 * @param String name The name of the attribute to be used to get metadata (optional)
 * @cat Plugins/Metadata
 * @descr Sets the type of encoding to be used when loading metadata for the first time
 * @type undefined
 * @see metadata()
 */

(function($) {

$.extend({
	metadata : {
		defaults : {
			type: 'class',
			name: 'metadata',
			cre: /({.*})/,
			single: 'metadata'
		},
		setType: function( type, name ){
			this.defaults.type = type;
			this.defaults.name = name;
		},
		get: function( elem, opts ){
			var settings = $.extend({},this.defaults,opts);
			// check for empty string in single property
			if ( !settings.single.length ) settings.single = 'metadata';
			
			var data = $.data(elem, settings.single);
			// returned cached data if it already exists
			if ( data ) return data;
			
			data = "{}";
			
			if ( settings.type == "class" ) {
				var m = settings.cre.exec( elem.className );
				if ( m )
					data = m[1];
			} else if ( settings.type == "elem" ) {
				if( !elem.getElementsByTagName )
					return undefined;
				var e = elem.getElementsByTagName(settings.name);
				if ( e.length )
					data = $.trim(e[0].innerHTML);
			} else if ( elem.getAttribute != undefined ) {
				var attr = elem.getAttribute( settings.name );
				if ( attr )
					data = attr;
			}
			
			if ( data.indexOf( '{' ) <0 )
			data = "{" + data + "}";
			
			data = eval("(" + data + ")");
			
			$.data( elem, settings.single, data );
			return data;
		}
	}
});

/**
 * Returns the metadata object for the first member of the jQuery object.
 *
 * @name metadata
 * @descr Returns element's metadata object
 * @param Object opts An object contianing settings to override the defaults
 * @type jQuery
 * @cat Plugins/Metadata
 */
$.fn.metadata = function( opts ){
	return $.metadata.get( this[0], opts );
};

})(jQuery);

/*
 * jQuery Media Plugin for converting elements into rich media content.
 *
 * Examples and documentation at: http://malsup.com/jquery/media/
 * Copyright (c) 2007-2008 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * @author: M. Alsup
 * @version: 0.81 (06/05/2008)
 * @requires jQuery v1.1.2 or later
 * $Id: jquery.media.js 2460 2007-07-23 02:53:15Z malsup $
 *
 * Supported Media Players:
 *    - Flash
 *    - Quicktime
 *    - Real Player
 *    - Silverlight
 *    - Windows Media Player
 *    - iframe
 *
 * Supported Media Formats:
 *   Any types supported by the above players, such as:
 *     Video: asf, avi, flv, mov, mpg, mpeg, mp4, qt, smil, swf, wmv, 3g2, 3gp
 *     Audio: aif, aac, au, gsm, mid, midi, mov, mp3, m4a, snd, rm, wav, wma
 *     Other: bmp, html, pdf, psd, qif, qtif, qti, tif, tiff, xaml
 *
 * Thanks to Mark Hicken and Brent Pedersen for helping me debug this on the Mac!
 * Thanks to Dan Rossi for numerous bug reports and code bits!
 */
;(function($) {

/**
 * Chainable method for converting elements into rich media.
 *
 * @param options
 * @param callback fn invoked for each matched element before conversion
 * @param callback fn invoked for each matched element after conversion
 */
$.fn.media = function(options, f1, f2) {
    return this.each(function() {
        if (typeof options == 'function') {
            f2 = f1;
            f1 = options;
            options = {};
        }
        var o = getSettings(this, options);
        // pre-conversion callback, passes original element and fully populated options
        if (typeof f1 == 'function') f1(this, o);
        
        var r = getTypesRegExp();
        var m = r.exec(o.src) || [''];
        o.type ? m[0] = o.type : m.shift();
        for (var i=0; i < m.length; i++) {
            fn1 = m[i].toLowerCase();
            if (isDigit(fn1[0])) fn1 = 'fn' + fn1; // fns can't begin with numbers
            if (!$.fn.media[fn1]) 
                continue;  // unrecognized media type
            // normalize autoplay settings
            var player = $.fn.media[fn1+'_player'];
            if (!o.params) o.params = {};
            if (player) {
                var num = player.autoplayAttr == 'autostart';
                o.params[player.autoplayAttr || 'autoplay'] = num ? (o.autoplay ? 1 : 0) : o.autoplay ? true : false;
            }
            var $div = $.fn.media[fn1](this, o);

            $div.css('backgroundColor', o.bgColor).width(o.width);
            // post-conversion callback, passes original element, new div element and fully populated options
            if (typeof f2 == 'function') f2(this, $div[0], o, player.name);
            break;
        }
    });
};

/**
 * Non-chainable method for adding or changing file format / player mapping
 * @name mapFormat
 * @param String format File format extension (ie: mov, wav, mp3)
 * @param String player Player name to use for the format (one of: flash, quicktime, realplayer, winmedia, silverlight or iframe
 */
$.fn.media.mapFormat = function(format, player) {
    if (!format || !player || !$.fn.media.defaults.players[player]) return; // invalid
    format = format.toLowerCase();
    if (isDigit(format[0])) format = 'fn' + format;
    $.fn.media[format] = $.fn.media[player];
    $.fn.media[format+'_player'] = $.fn.media.defaults.players[player];
};

// global defautls; override as needed
$.fn.media.defaults = {
    width:         400,
    height:        400,
    autoplay:      0,         // normalized cross-player setting
    bgColor:       '#ffffff', // background color
    params:        { wmode: 'transparent'},  // added to object element as param elements; added to embed element as attrs
    attrs:         {},        // added to object and embed elements as attrs
    flashvars:     {},        // added to flash content as flashvars param/attr
    flashVersion:  '7',       // required flash version
    expressInstaller: null,   // src for express installer
    
    // default flash video and mp3 player (@see: http://jeroenwijering.com/?item=Flash_Media_Player)
    flvPlayer:     'mediaplayer.swf',
    mp3Player:     'mediaplayer.swf',
    
    // @see http://msdn2.microsoft.com/en-us/library/bb412401.aspx
    silverlight: {
        inplaceInstallPrompt: 'true', // display in-place install prompt?
        isWindowless:         'true', // windowless mode (false for wrapping markup)
        framerate:            '24',   // maximum framerate
        version:              '0.9',  // Silverlight version
        onError:              null,   // onError callback
        onLoad:               null,   // onLoad callback
        initParams:           null,   // object init params
        userContext:          null    // callback arg passed to the load callback
    }
};

// Media Players; think twice before overriding
$.fn.media.defaults.players = {
    flash: {
        name:         'flash',
        types:        'flv,mp3,swf',
        oAttrs:   {
            classid:  'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000',
            type:     'application/x-oleobject',
            codebase: 'http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' + $.fn.media.defaults.flashVersion
        },
        eAttrs: {
            type:         'application/x-shockwave-flash',
            pluginspage:  'http://www.adobe.com/go/getflashplayer'
        }        
    },
    quicktime: {
        name:         'quicktime',
        types:        'aif,aiff,aac,au,bmp,gsm,mov,mid,midi,mpg,mpeg,mp4,m4a,psd,qt,qtif,qif,qti,snd,tif,tiff,wav,3g2,3gp',
        oAttrs:   {
            classid:  'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B',
            codebase: 'http://www.apple.com/qtactivex/qtplugin.cab'
        },
        eAttrs: {
            pluginspage:  'http://www.apple.com/quicktime/download/'
        }
    },
    realplayer: {
        name:         'real',
        types:        'ra,ram,rm,rpm,rv,smi,smil',
        autoplayAttr: 'autostart',
        oAttrs:   {
            classid:  'clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA'
        },
        eAttrs: {
            type:         'audio/x-pn-realaudio-plugin',
            pluginspage:  'http://www.real.com/player/'
        }
    },
    winmedia: {
        name:         'winmedia',
        types:        'asf,avi,wma,wmv',
        autoplayAttr: 'autostart',
        oUrl:         'url',
        oAttrs:   {
            classid:  'clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6',
            type:     'application/x-oleobject'
        },
        eAttrs: {
            type:         $.browser.mozilla && isFirefoxWMPPluginInstalled() ? 'application/x-ms-wmp' : 'application/x-mplayer2',
            pluginspage:  'http://www.microsoft.com/Windows/MediaPlayer/'
        }        
    },
    // special cases
    iframe: {
        name:  'iframe',
        types: 'html,pdf'
    },
    silverlight: {
        name:  'silverlight',
        types: 'xaml'
    }
};

//
//  everything below here is private
//


// detection script for FF WMP plugin (http://www.therossman.org/experiments/wmp_play.html)
// (hat tip to Mark Ross for this script)
function isFirefoxWMPPluginInstalled() {
    var plugs = navigator.plugins;
    for (i = 0; i < plugs.length; i++) {
        var plugin = plugs[i];
        if (plugin['filename'] == 'np-mswmp.dll')
            return true;
    }
    return false;
}

var counter = 1;

for (var player in $.fn.media.defaults.players) {
    var types = $.fn.media.defaults.players[player].types;
    $.each(types.split(','), function(i,o) {
        if (isDigit(o[0])) o = 'fn' + o;
        $.fn.media[o] = $.fn.media[player] = getGenerator(player);
        $.fn.media[o+'_player'] = $.fn.media.defaults.players[player];
    });
};

function getTypesRegExp() {
    var types = '';
    for (var player in $.fn.media.defaults.players) {
        if (types.length) types += ',';
        types += $.fn.media.defaults.players[player].types;
    };
    return new RegExp('\\.(' + types.replace(/,/g,'|') + ')\\b');
};

function getGenerator(player) {
    return function(el, options) {
        return generate(el, options, player);
    };
};

function isDigit(c) {
    return '0123456789'.indexOf(c) > -1;
};

// flatten all possible options: global defaults, meta, option obj
function getSettings(el, options) {
    options = options || {};
    var $el = $(el);
    var cls = el.className || '';
    // support metadata plugin (v1.0 and v2.0)
    var meta = $.metadata ? $el.metadata() : $.meta ? $el.data() : {};
    meta = meta || {};
    var w = meta.width  || parseInt(((cls.match(/w:(\d+)/)||[])[1]||0));
    var h = meta.height || parseInt(((cls.match(/h:(\d+)/)||[])[1]||0));
    
    if (w) meta.width  = w;
    if (h) meta.height = h;
    if (cls) meta.cls = cls;

    var a = $.fn.media.defaults;
    var b = options;
    var c = meta;

    var p = { params: { bgColor: options.bgColor || $.fn.media.defaults.bgColor } };
    var opts = $.extend({}, a, b, c);
    $.each(['attrs','params','flashvars','silverlight'], function(i,o) {
        opts[o] = $.extend({}, p[o] || {}, a[o] || {}, b[o] || {}, c[o] || {});
    });

    if (typeof opts.caption == 'undefined') opts.caption = $el.text();

    // make sure we have a source!
    opts.src = opts.src || $el.attr('href') || $el.attr('src') || 'unknown';
    return opts;
};

//
//  Flash Player
//

// generate flash using SWFObject library if possible
$.fn.media.swf = function(el, opts) {
    if (!window.SWFObject && !window.swfobject) {
        // roll our own
        if (opts.flashvars) {
            var a = [];
            for (var f in opts.flashvars)
                a.push(f + '=' + opts.flashvars[f]);
            if (!opts.params) opts.params = {};
            opts.params.flashvars = a.join('&');
        }
        return generate(el, opts, 'flash');
    }

    var id = el.id ? (' id="'+el.id+'"') : '';
    var cls = opts.cls ? (' class="' + opts.cls + '"') : '';
    var $div = $('<div' + id + cls + '>');

    // swfobject v2+
    if (window.swfobject) {
        $(el).after($div).appendTo($div);
        if (!el.id) el.id = 'movie_player_' + counter++;

        // replace el with swfobject content
        swfobject.embedSWF(opts.src, el.id, opts.width, opts.height, opts.flashVersion, 
            opts.expressInstaller, opts.flashvars, opts.params, opts.attrs);
    }
    // swfobject < v2
    else {
        $(el).after($div).remove();
        var so = new SWFObject(opts.src, 'movie_player_' + counter++, opts.width, opts.height, opts.flashVersion, opts.bgColor);
        if (opts.expressInstaller) so.useExpressInstall(opts.expressInstaller);    

        for (var p in opts.params)
            if (p != 'bgColor') so.addParam(p, opts.params[p]);
        for (var f in opts.flashvars)
            so.addVariable(f, opts.flashvars[f]);
        so.write($div[0]);
    }

    if (opts.caption) $('<div>').appendTo($div).html(opts.caption);
    return $div;
};

// map flv and mp3 files to the swf player by default
$.fn.media.flv = $.fn.media.mp3 = function(el, opts) {
    var src = opts.src;
    var player = /\.mp3\b/i.test(src) ? $.fn.media.defaults.mp3Player : $.fn.media.defaults.flvPlayer;
    opts.src = player;
    opts.src = opts.src + '?file=' + src;
    opts.flashvars = $.extend({}, { file: src }, opts.flashvars );
    return $.fn.media.swf(el, opts);
};

//
//  Silverlight
//
$.fn.media.xaml = function(el, opts) {
    if (!window.Sys || !window.Sys.Silverlight) {
        if ($.fn.media.xaml.warning) return;
        $.fn.media.xaml.warning = 1;
        alert('You must include the Silverlight.js script.');
        return;
    }

    var props = {
        width: opts.width,
        height: opts.height,
        background: opts.bgColor,
        inplaceInstallPrompt: opts.silverlight.inplaceInstallPrompt,
        isWindowless: opts.silverlight.isWindowless,
        framerate: opts.silverlight.framerate,
        version: opts.silverlight.version
    };
    var events = {
        onError: opts.silverlight.onError,
        onLoad: opts.silverlight.onLoad
    };

    var id1 = el.id ? (' id="'+el.id+'"') : '';
    var id2 = opts.id || 'AG' + counter++;
    // convert element to div
    var cls = opts.cls ? (' class="' + opts.cls + '"') : '';
    var $div = $('<div' + id1 + cls + '>');
    $(el).after($div).remove();
    
    Sys.Silverlight.createObjectEx({


        source: opts.src,
        initParams: opts.silverlight.initParams,
        userContext: opts.silverlight.userContext,
        id: id2,
        parentElement: $div[0],
        properties: props,
        events: events
    });

    if (opts.caption) $('<div>').appendTo($div).html(opts.caption);
    return $div;
};

//
// generate object/embed markup
//
function generate(el, opts, player) {
    var $el = $(el);
    var o = $.fn.media.defaults.players[player];
    
    if (player == 'iframe') {
        var o = $('<iframe' + ' width="' + opts.width + '" height="' + opts.height + '" >');
        o.attr('src', opts.src);
        o.css('backgroundColor', o.bgColor);
    }
    else if ($.browser.msie) {
        var a = ['<object width="' + opts.width + '" height="' + opts.height + '" '];
        for (var key in opts.attrs)
            a.push(key + '="'+opts.attrs[key]+'" ');
        for (var key in o.oAttrs || {})
            a.push(key + '="'+o.oAttrs[key]+'" ');
        a.push('></ob'+'ject'+'>');
        var p = ['<param name="' + (o.oUrl || 'src') +'" value="' + opts.src + '">'];
        for (var key in opts.params)
            p.push('<param name="'+ key +'" value="' + opts.params[key] + '">');
        var o = document.createElement(a.join(''));
        for (var i=0; i < p.length; i++)
            o.appendChild(document.createElement(p[i]));
    }
    else {
        var a = ['<embed width="' + opts.width + '" height="' + opts.height + '" style="display:block"'];
        if (opts.src) a.push(' src="' + opts.src + '" ');
        for (var key in opts.attrs)
            a.push(key + '="'+opts.attrs[key]+'" ');
        for (var key in o.eAttrs || {})
            a.push(key + '="'+o.eAttrs[key]+'" ');
        for (var key in opts.params)
            a.push(key + '="'+opts.params[key]+'" ');
        a.push('></em'+'bed'+'>');
    }
    // convert element to div
    var id = el.id ? (' id="'+el.id+'"') : '';
    var cls = opts.cls ? (' class="' + opts.cls + '"') : '';
    var $div = $('<div' + id + cls + '>');
    $el.after($div).remove();
    ($.browser.msie || player == 'iframe') ? $div.append(o) : $div.html(a.join(''));
    if (opts.caption) $('<div>').appendTo($div).html(opts.caption);
    return $div;
};


})(jQuery);

var ping_error_count = 0;

var mousexy = {x:0,y:0};
var memxy=null;
var fl_check_game_in=true;
var fl_check_skin_count = false;

function infoAutoHide() {
   setTimeout('$(".sinf_tbl").fadeOut("slow");',5000);
}

function errorAutoHide() {
   setTimeout('$(".serr_tbl").fadeOut("slow");',5000);
}

function _debug(s) {
  $('div#debug').html($('div#debug').html()+'<br>'+s);
}

function doCLInfo(id) {
   location.href="/?cl_stat="+id;
}

function doTopic(id) {
  $.blockUI({message:'<img src="/images/wait_w.gif" border="0" alt=""/>'});
  $.post('?',{jajax:"do_topic",id_topic:id},function(xml) {
      $.unblockUI();
      $('td#body_ontop_html').html($("html",xml).text());
      $('div#body_ontop').show();
  });
}

function doMenu(id) {
  $.blockUI({message:'<img src="/images/wait_w.gif" border="0" alt=""/>'});
  $.post('?',{jajax:"do_menu_topic",id_menu:id},function(xml) {
      $.unblockUI();
      $('td#body_ontop_html').html($("html",xml).text());
      $('div#body_ontop').show();
  });
}


function checkGameIn() {
  if (typeof(__id_game)=='undefined') {
    if (fl_check_game_in) {
      $.post('?',{jajax:"check_game_in"},function(xml) {
        to_game=$("to_game",xml).text();
        id_wait=$("id_wait",xml).text();
        if (to_game>0) {location.href="?mf_game="+to_game;}
        if (id_wait==0) {fl_check_game_in=false;}
    });
    }
    setTimeout('checkGameIn();',__to_st_games);
  }
}

function skin_count() {
  if (__id_client>0) {

       if (!fl_check_skin_count) {
           fl_check_skin_count=true;
           $.post('?',{jajax:"mf_skin_count"},function(xml) {

               ar_s = $("s_skins",xml).text(); ar_s = ar_s.split(',');
               for (i=0; i<ar_s.length; i++) {
                  $('div#id_tab_skin_'+ar_s[i]).attr('title','игроков на улице: '+$("clcous_"+ar_s[i],xml).text()); 
                  cou=parseInt($("clcous_"+ar_s[i],xml).text()); if (cou>0) {s=' ('+cou+')';} else {s='';}
                  $('div#id_skin_count_'+ar_s[i]).html(s); 
               }
               ar_sl = $("s_skinlvl",xml).text(); ar_sl = ar_sl.split(',');
               for (i=0; i<ar_sl.length; i++) {
                  $('a#id_a_lvl_'+ar_sl[i]).attr('title','игроков на улице: '+$("clcousl_"+ar_sl[i],xml).text()); 
               }
              
              fl_check_skin_count = false;

           });
       }

    setTimeout('skin_count();',__to_st_chat);
  }
}

function doCLInfoFloat(id) {
   $.blockUI({message:'<img src="/images/wait_gr.gif" border="0" alt=""/>'});
   $.post('?',{jajax:"mf-cl-stat", id:id},function(xml) {
        $.unblockUI();
        $('#id_cl_stat_html').html($("html",xml).text());
        $("#id_cl_stat").animate({left: 20, top:20, width:$(window).width()-200, height:$(window).height()-80, opacity: 'show'}, 500);
  });
}


function doWindowResize() {
               $('div#body_ontop').css({width:$(window).width()-40});
               $('div#body_ontop').css({height:$(window).height()-40});
}

$(window).resize(function() {
   doWindowResize();
});

$(document).ready(function() {

                jQuery(document).bind('mousemove',function(e){mousexy.x=e.pageX; mousexy.y=e.pageY;});

                $.blockUI.defaults.css.backgroundColor='';
                $.blockUI.defaults.css.border='none';
                $.blockUI.defaults.overlayCSS.backgroundColor='#333333';
                $.blockUI.defaults.overlayCSS.opacity=0.8;
                $.blockUI.defaults.baseZ=99999;

//                jstime();

                if (__vs!='mf_street') {checkGameIn();}

                if (__id_client>0 && ((__id_game<1 && __vs!='mf_street'))) {
                     checkMailINTimeOut();
                     checkMailINCountTimeOut();
                }

               doWindowResize();

               if ((typeof(__id_game)=='undefined' || __id_game<1) && __vs!='mf_street') {
                  skin_count();
               }

              errorAutoHide();
              infoAutoHide()

//alert($(window).height()+' '+$(window).width());

//$('li').each(function() {_debug(this.innerHTML+' '+this.className);});

});

function doMFClients(ssby,sp) {
//    location.href="?vs=clients&fclean=1";
   if (!ssby) ssby='';
   if (!sp) sp=0;
  $.blockUI({message:'<img src="/images/wait_gr.gif" border="0" alt=""/>'});
  $.post('?',{jajax:"mf_clients",fclean:1,sp:sp,ssby:ssby},function(xml) {
      $.unblockUI();
      $('td#body_ontop_title').html('Игроки');
      $('td#body_ontop_html').html($("html",xml).text()+'<script>'+$("js",xml).text()+'</script>');
      $('div#body_ontop').show();
  });
}

function doMFGames(ssby,sp,idcl,idtour) {
//   location.href="?vs=mf_games&fclean=1";
   if (!ssby) ssby='';
   if (!sp) sp=0;
   if (!idcl) idcl=0;
   if (!idtour) idtour=0;
  $.blockUI({message:'<img src="/images/wait_gr.gif" border="0" alt=""/>'});
  $.post('?',{jajax:"mf_games",fclean:1,sp:sp,ssby:ssby,idcl:idcl,idtour:idtour},function(xml) {
      $.unblockUI();
      $('td#body_ontop_title').html('Партии');
      $('td#body_ontop_html').html($("html",xml).text()+'<script>'+$("js",xml).text()+'</script>');
      $('div#body_ontop').show();
  });
}

  function checkLogin() {
    s=document.form_login_remind.eemail.value;
    if(s.length<1){alert("Ошибка! Поле адреса не может быть пустым!"); return false;}
    return true;
  }

/*
 * jQuery blockUI plugin
 * Version 2.16 (20-MAR-2009)
 * @requires jQuery v1.2.3 or later
 *
 * Examples at: http://malsup.com/jquery/block/
 * Copyright (c) 2007-2008 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Thanks to Amir-Hossein Sobhi for some excellent contributions!
 */

;(function($) {

if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
    alert('blockUI requires jQuery v1.2.3 or later!  You are using v' + $.fn.jquery);
    return;
}

$.fn._fadeIn = $.fn.fadeIn;

// global $ methods for blocking/unblocking the entire page
$.blockUI   = function(opts) { install(window, opts); };
$.unblockUI = function(opts) { remove(window, opts); };

// convenience method for quick growl-like notifications  (http://www.google.com/search?q=growl)
$.growlUI = function(title, message, timeout) {
	var $m = $('<div class="growlUI"></div>');
	if (title) $m.append('<h1>'+title+'</h1>');
	if (message) $m.append('<h2>'+message+'</h2>');
	if (timeout == undefined) timeout = 3000;
    $.blockUI({
		message: $m, fadeIn: 700, fadeOut: 1000, centerY: false,
		timeout: timeout, showOverlay: false,
		css: $.blockUI.defaults.growlCSS
    });
};

// plugin method for blocking element content
$.fn.block = function(opts) {
    return this.each(function() {
        if ($.css(this,'position') == 'static')
            this.style.position = 'relative';
        if ($.browser.msie)
            this.style.zoom = 1; // force 'hasLayout'
        install(this, opts);
    });
};

// plugin method for unblocking element content
$.fn.unblock = function(opts) {
    return this.each(function() {
        remove(this, opts);
    });
};

$.blockUI.version = 2.16; // 2nd generation blocking at no extra cost!

// override these in your code to change the default behavior and style
$.blockUI.defaults = {
    // message displayed when blocking (use null for no message)
    message:  '<h1>Please wait...</h1>',

    // styles for the message when blocking; if you wish to disable
    // these and use an external stylesheet then do this in your code:
    // $.blockUI.defaults.css = {};
    css: {
        padding:        0,
        margin:         0,
        width:          '30%',
        top:            '40%',
        left:           '35%',
        textAlign:      'center',
        color:          '#000',
        border:         '3px solid #aaa',
        backgroundColor:'#fff',
        cursor:         'wait'
    },

    // styles for the overlay
    overlayCSS:  {
        backgroundColor: '#000',
        opacity:         '0.6'
    },

	// styles applied when using $.growlUI
	growlCSS: {
		width:    '350px',
		top:      '10px',
		left:     '',
		right:    '10px',
	    border:   'none',
	    padding:  '5px',
	    opacity:  '0.6',
		cursor:    null,
	    color:    '#fff',
	    backgroundColor: '#000',
	    '-webkit-border-radius': '10px',
	    '-moz-border-radius':    '10px'
	},

    // z-index for the blocking overlay
    baseZ: 1000,

    // set these to true to have the message automatically centered
    centerX: true, // <-- only effects element blocking (page block controlled via css above)
    centerY: true,

    // allow body element to be stetched in ie6; this makes blocking look better
    // on "short" pages.  disable if you wish to prevent changes to the body height
    allowBodyStretch: true,

    // be default blockUI will supress tab navigation from leaving blocking content;
    constrainTabKey: true,

    // fadeIn time in millis; set to 0 to disable fadeIn on block
    fadeIn:  200,

    // fadeOut time in millis; set to 0 to disable fadeOut on unblock
    fadeOut:  400,

	// time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock
	timeout: 0,

	// disable if you don't want to show the overlay
	showOverlay: true,

    // if true, focus will be placed in the first available input field when
    // page blocking
    focusInput: true,

    // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
    applyPlatformOpacityRules: true,

    // callback method invoked when unblocking has completed; the callback is
    // passed the element that has been unblocked (which is the window object for page
    // blocks) and the options that were passed to the unblock call:
    //     onUnblock(element, options)
    onUnblock: null,

    // don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493
    quirksmodeOffsetHack: 4
};

// private data and functions follow...

var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent);
var pageBlock = null;
var pageBlockEls = [];

function install(el, opts) {
    var full = (el == window);
    var msg = opts && opts.message !== undefined ? opts.message : undefined;
    opts = $.extend({}, $.blockUI.defaults, opts || {});
    opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
    var css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
    msg = msg === undefined ? opts.message : msg;

    // remove the current block (if there is one)
    if (full && pageBlock)
        remove(window, {fadeOut:0});

    // if an existing element is being used as the blocking content then we capture
    // its current place in the DOM (and current display style) so we can restore
    // it when we unblock
    if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
        var node = msg.jquery ? msg[0] : msg;
        var data = {};
        $(el).data('blockUI.history', data);
        data.el = node;
        data.parent = node.parentNode;
        data.display = node.style.display;
        data.position = node.style.position;
		if (data.parent)
			data.parent.removeChild(node);
    }

    var z = opts.baseZ;

    // blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
    // layer1 is the iframe layer which is used to supress bleed through of underlying content
    // layer2 is the overlay layer which has opacity and a wait cursor
    // layer3 is the message content that is displayed while blocking

    var lyr1 = ($.browser.msie) ? $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="about:blank"></iframe>')
                                : $('<div class="blockUI" style="display:none"></div>');
    var lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;cursor:wait;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
    var lyr3 = full ? $('<div class="blockUI blockMsg blockPage" style="z-index:'+z+';display:none;position:fixed"></div>')
                    : $('<div class="blockUI blockMsg blockElement" style="z-index:'+z+';display:none;position:absolute"></div>');

    // if we have a message, style it
    if (msg)
        lyr3.css(css);

    // style the overlay
    if (!opts.applyPlatformOpacityRules || !($.browser.mozilla && /Linux/.test(navigator.platform)))
        lyr2.css(opts.overlayCSS);
    lyr2.css('position', full ? 'fixed' : 'absolute');

    // make iframe layer transparent in IE
    if ($.browser.msie)
        lyr1.css('opacity','0.0');

    $([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);

    // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
    var expr = $.browser.msie && ($.browser.version < 8 || !$.boxModel) && (!$.boxModel || $('object,embed', full ? null : el).length > 0);
    if (ie6 || expr && lyr3[0].style.setExpression) {
        // give body 100% height
        if (full && opts.allowBodyStretch && $.boxModel)
            $('html,body').css('height','100%');

        // fix ie6 issue when blocked element has a border width
        if ((ie6 || !$.boxModel) && !full) {
            var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
            var fixT = t ? '(0 - '+t+')' : 0;
            var fixL = l ? '(0 - '+l+')' : 0;
        }

        // simulate fixed position
        $.each([lyr1,lyr2,lyr3], function(i,o) {
            var s = o[0].style;
            s.position = 'absolute';
            if (i < 2) {
                full ? s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"')
                     : s.setExpression('height','this.parentNode.offsetHeight + "px"');
                full ? s.setExpression('width','jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"')
                     : s.setExpression('width','this.parentNode.offsetWidth + "px"');
                if (fixL) s.setExpression('left', fixL);
                if (fixT) s.setExpression('top', fixT);
            }
            else if (opts.centerY) {
                if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
                s.marginTop = 0;
            }
			else if (!opts.centerY && full) {
				var top = (opts.css && opts.css.top) ? parseInt(opts.css.top) : 0;
				var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"';
                s.setExpression('top',expression);
			}
        });
    }

    // show the message
	if (msg) {
		lyr3.append(msg);
		if (msg.jquery || msg.nodeType)
			$(msg).show();
	}

	if ($.browser.msie && opts.showOverlay)
		lyr1.show(); // opacity is zero
	if (opts.fadeIn) {
		if (opts.showOverlay)
			lyr2._fadeIn(opts.fadeIn);
		if (msg)
			lyr3.fadeIn(opts.fadeIn);
	}
	else {
		if (opts.showOverlay)
			lyr2.show();
		if (msg)
			lyr3.show();
	}

    // bind key and mouse events
    bind(1, el, opts);

    if (full) {
        pageBlock = lyr3[0];
        pageBlockEls = $(':input:enabled:visible',pageBlock);
        if (opts.focusInput)
            setTimeout(focus, 20);
    }
    else
        center(lyr3[0], opts.centerX, opts.centerY);

	if (opts.timeout) {
		// auto-unblock
		var to = setTimeout(function() {
			full ? $.unblockUI(opts) : $(el).unblock(opts);
		}, opts.timeout);
		$(el).data('blockUI.timeout', to);
	}
};

// remove the block
function remove(el, opts) {
    var full = el == window;
	var $el = $(el);
    var data = $el.data('blockUI.history');
	var to = $el.data('blockUI.timeout');
	if (to) {
		clearTimeout(to);
		$el.removeData('blockUI.timeout');
	}
    opts = $.extend({}, $.blockUI.defaults, opts || {});
    bind(0, el, opts); // unbind events
    var els = full ? $('body').children().filter('.blockUI') : $('.blockUI', el);

    if (full)
        pageBlock = pageBlockEls = null;

    if (opts.fadeOut) {
        els.fadeOut(opts.fadeOut);
        setTimeout(function() { reset(els,data,opts,el); }, opts.fadeOut);
    }
    else
        reset(els, data, opts, el);
};

// move blocking element back into the DOM where it started
function reset(els,data,opts,el) {
    els.each(function(i,o) {
        // remove via DOM calls so we don't lose event handlers
        if (this.parentNode)
            this.parentNode.removeChild(this);
    });

    if (data && data.el) {
        data.el.style.display = data.display;
        data.el.style.position = data.position;
		if (data.parent)
			data.parent.appendChild(data.el);
        $(data.el).removeData('blockUI.history');
    }

    if (typeof opts.onUnblock == 'function')
        opts.onUnblock(el,opts);
};

// bind/unbind the handler
function bind(b, el, opts) {
    var full = el == window, $el = $(el);

    // don't bother unbinding if there is nothing to unbind
    if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked')))
        return;
    if (!full)
        $el.data('blockUI.isBlocked', b);

    if (b && !opts.showOverlay) // don't prevent events when overlay not in use
		return;

    // bind anchors and inputs for mouse and key events
    var events = 'mousedown mouseup keydown keypress';
    b ? $(document).bind(events, opts, handler) : $(document).unbind(events, handler);

// former impl...
//    var $e = $('a,:input');
//    b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
};

// event handler to suppress keyboard/mouse events when blocking
function handler(e) {
    // allow tab navigation (conditionally)
    if (e.keyCode && e.keyCode == 9) {
        if (pageBlock && e.data.constrainTabKey) {
            var els = pageBlockEls;
            var fwd = !e.shiftKey && e.target == els[els.length-1];
            var back = e.shiftKey && e.target == els[0];
            if (fwd || back) {
                setTimeout(function(){focus(back)},10);
                return false;
            }
        }
    }
    // allow events within the message content
    if ($(e.target).parents('div.blockMsg').length > 0)
        return true;

    // allow events for content that is not being blocked
    return $(e.target).parents().children().filter('div.blockUI').length == 0;
};

function focus(back) {
    if (!pageBlockEls)
        return;
    var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
    if (e)
        e.focus();
};

function center(el, x, y) {
    var p = el.parentNode, s = el.style;
    var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
    var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
    if (x) s.left = l > 0 ? (l+'px') : '0';
    if (y) s.top  = t > 0 ? (t+'px') : '0';
};

function sz(el, p) {
    return parseInt($.css(el,p))||0;
};

})(jQuery);

(function($) {

  $.fn.jtimer = function(start_sec, options, callback) {
    var version = '0.1a';

    var opts = $.extend({}, $.fn.jtimer.defaults, options);
         
    return this.each(function() {
      $this = $(this);
      $this.timerID = null;
      $this.running = false;
			$this.start_sec = start_sec;
			if (!callback) {
			  $this.callback = null;
			} else {
			  $this.callback = callback;
			}

      var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

      $this.fl_h = o.fl_h;
      $this.sec_end = o.sec_end;

      $.fn.jtimer.startTimer($this);

    });
  };
       
  $.fn.jtimer.startTimer = function(el) {
    $.fn.jtimer.stopTimer(el);
    $.fn.jtimer.displayTime(el);
  }
  $.fn.jtimer.stopTimer = function(el) {
    if(el.running) {
      clearTimeout(el.timerID);
    }
    el.running = false;
  }
  $.fn.jtimer.displayTime = function(el) {
		if (el.start_sec>=0) {
			s=el.start_sec % 60;
			m=Math.floor(el.start_sec/60);
			if (el.fl_h) {
				h=Math.floor(m/60);
				m=m % 60;
				h = h<10 ? h='0'+h+':' : h+':';
			} else {
			  h='';
			}
			m = m<10 ? m='0'+m+':' : m+':';
			s = s<10 ? s='0'+s : s;
			el.html(h+m+s);
			if ((el.start_sec>0 && el.sec_end==0) || el.sec_end==-1 || (el.sec_end>0 && el.start_sec<el.sec_end)) {
				if (el.sec_end==0) {el.start_sec--;} else {el.start_sec++;}
			  el.timerID = setTimeout(function(){$.fn.jtimer.displayTime(el)},1000);
		  } else {
				$.fn.jtimer.stopTimer(el);
				if (el.callback) el.callback();
		  }	
    }
  }
       
  $.fn.jtimer.defaults = {
	fl_h: false,
        sec_end:0  // 0 - minus, >0 - end, -1 +бесконечность  
  };

})(jQuery);

var fl_open_smiles = false;
var currSmileIndex = -1;
var currSmileIMG = false;

function closeSmileStreet() {
  $('#id_smiles_street').hide();
  $('input#_st_mess').focus();
  fl_open_smiles = false;
}

function setSmileSelNext(delta) {
  length=52;
  prevIndex=currSmileIndex;
  currSmileIndex+=delta;  if (currSmileIndex>=length) currSmileIndex=0; if (currSmileIndex<0) currSmileIndex=length-1;
  $('img[idx='+prevIndex+']').removeClass();  $('img[idx='+prevIndex+']').addClass('smile');
  $('img[idx='+currSmileIndex+']').removeClass();  $('img[idx='+currSmileIndex+']').addClass('smile_sel');
  currSmileIMG=$('img[idx='+currSmileIndex+']')[0];
}

$(document).ready(function() {
  $('.smile').each(function(index,item) {$(item).attr('idx',index)});
});

function doSkin(sv,id_tour) {
  location.href="/?mfskin="+sv+"&mftour="+id_tour;
}

/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-12-20 08:43:48 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4257 $
 *
 * Version: 1.2
 *
 * Requires: jQuery 1.2+
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(5($){$.19={P:\'1.2\'};$.u([\'j\',\'w\'],5(i,d){$.q[\'O\'+d]=5(){p(!3[0])6;g a=d==\'j\'?\'s\':\'m\',e=d==\'j\'?\'D\':\'C\';6 3.B(\':y\')?3[0][\'L\'+d]:4(3,d.x())+4(3,\'n\'+a)+4(3,\'n\'+e)};$.q[\'I\'+d]=5(b){p(!3[0])6;g c=d==\'j\'?\'s\':\'m\',e=d==\'j\'?\'D\':\'C\';b=$.F({t:Z},b||{});g a=3.B(\':y\')?3[0][\'8\'+d]:4(3,d.x())+4(3,\'E\'+c+\'w\')+4(3,\'E\'+e+\'w\')+4(3,\'n\'+c)+4(3,\'n\'+e);6 a+(b.t?(4(3,\'t\'+c)+4(3,\'t\'+e)):0)}});$.u([\'m\',\'s\'],5(i,b){$.q[\'l\'+b]=5(a){p(!3[0])6;6 a!=W?3.u(5(){3==h||3==r?h.V(b==\'m\'?a:$(h)[\'U\'](),b==\'s\'?a:$(h)[\'T\']()):3[\'l\'+b]=a}):3[0]==h||3[0]==r?S[(b==\'m\'?\'R\':\'Q\')]||$.N&&r.M[\'l\'+b]||r.A[\'l\'+b]:3[0][\'l\'+b]}});$.q.F({z:5(){g a=0,f=0,o=3[0],8,9,7,v;p(o){7=3.7();8=3.8();9=7.8();8.f-=4(o,\'K\');8.k-=4(o,\'J\');9.f+=4(7,\'H\');9.k+=4(7,\'Y\');v={f:8.f-9.f,k:8.k-9.k}}6 v},7:5(){g a=3[0].7;G(a&&(!/^A|10$/i.16(a.15)&&$.14(a,\'z\')==\'13\'))a=a.7;6 $(a)}});5 4(a,b){6 12($.11(a.17?a[0]:a,b,18))||0}})(X);',62,72,'|||this|num|function|return|offsetParent|offset|parentOffset|||||borr|top|var|window||Height|left|scroll|Left|padding|elem|if|fn|document|Top|margin|each|results|Width|toLowerCase|visible|position|body|is|Right|Bottom|border|extend|while|borderTopWidth|outer|marginLeft|marginTop|client|documentElement|boxModel|inner|version|pageYOffset|pageXOffset|self|scrollTop|scrollLeft|scrollTo|undefined|jQuery|borderLeftWidth|false|html|curCSS|parseInt|static|css|tagName|test|jquery|true|dimensions'.split('|'),0,{}))

/* Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * $LastChangedDate: 2007-12-14 23:57:10 -0600 (Fri, 14 Dec 2007) $
 * $Rev: 4163 $
 *
 * Version: 3.0
 * 
 * Requires: $ 1.2.2+
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(5($){$.6.j.4={L:5(){9 b=$.6.j.4.i;7($.8.f)$(2).o(\'y.4\',5(a){$.d(2,\'h\',{x:a.x,l:a.l,s:a.s,r:a.r})});7(2.q)2.q(($.8.f?\'v\':\'4\'),b,n);m 2.w=b},D:5(){9 a=$.6.j.4.i;$(2).k(\'y.4\');7(2.u)2.u(($.8.f?\'v\':\'4\'),a,n);m 2.w=5(){};$.A(2,\'h\')},i:5(a){9 c=U.T.S.P(O,1);a=$.6.N(a||M.6);$.t(a,$.d(2,\'h\')||{});9 b=0,K=J;7(a.e)b=a.e/I;7(a.p)b=-a.p/3;7($.8.H)b=-a.e;a.d=a.d||{};a.G="4";c.z(b);c.z(a);g $.6.F.E(2,c)}};$.Q.t({4:5(a){g a?2.o("4",a):2.R("4")},C:5(a){g 2.k("4",a)}})})(B);',57,57,'||this||mousewheel|function|event|if|browser|var||||data|wheelDelta|mozilla|return|mwcursorposdata|handler|special|unbind|pageY|else|false|bind|detail|addEventListener|clientY|clientX|extend|removeEventListener|DOMMouseScroll|onmousewheel|pageX|mousemove|unshift|removeData|jQuery|unmousewheel|teardown|apply|handle|type|opera|120|true|returnValue|setup|window|fix|arguments|call|fn|trigger|slice|prototype|Array'.split('|'),0,{}))

/*
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */

;(function($){
	$.fn.superfish = function(op){

		var sf = $.fn.superfish,
			c = sf.c,
			$arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
			over = function(){
				var $$ = $(this), menu = getMenu($$);
				clearTimeout(menu.sfTimer);
				$$.showSuperfishUl().siblings().hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this), menu = getMenu($$), o = sf.op;
				clearTimeout(menu.sfTimer);
				menu.sfTimer=setTimeout(function(){
					o.retainPath=($.inArray($$[0],o.$path)>-1);
					$$.hideSuperfishUl();
					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
				},o.delay);	
			},
			getMenu = function($menu){
				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
				sf.op = sf.o[menu.serial];
				return menu;
			},
			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
			
		return this.each(function() {
			var s = this.serial = sf.o.length;
			var o = $.extend({},sf.defaults,op);
			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
					.filter('li:has(ul)').removeClass(o.pathClass);
			});
			sf.o[s] = sf.op = o;
			
			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
				if (o.autoArrows) addArrow( $('>a:first-child',this) );
			})
			.not('.'+c.bcClass)
				.hideSuperfishUl();
			
			var $a = $('a',this);
			$a.each(function(i){
				var $li = $a.eq(i).parents('li');
				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
			});
			o.onInit.call(this);
			
		}).each(function() {
			menuClasses = [c.menuClass];
			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
			$(this).addClass(menuClasses.join(' '));
		});
	};

	var sf = $.fn.superfish;
	sf.o = [];
	sf.op = {};
	sf.IE7fix = function(){
		var o = sf.op;
		if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
			this.toggleClass(sf.c.shadowClass+'-off');
		};
	sf.c = {
		bcClass     : 'sf-breadcrumb',
		menuClass   : 'sf-js-enabled',
		anchorClass : 'sf-with-ul',
		arrowClass  : 'sf-sub-indicator',
		shadowClass : 'sf-shadow'
	};
	sf.defaults = {
		hoverClass	: 'sfHover',
		pathClass	: 'overideThisToUse',
		pathLevels	: 1,
		delay		: 800,
		animation	: {opacity:'show'},
		speed		: 'normal',
		autoArrows	: true,
		dropShadows : true,
		disableHI	: false,		// true disables hoverIntent detection
		onInit		: function(){}, // callback functions
		onBeforeShow: function(){},
		onShow		: function(){},
		onHide		: function(){}
	};
	$.fn.extend({
		hideSuperfishUl : function(){
			var o = sf.op,
				not = (o.retainPath===true) ? o.$path : '';
			o.retainPath = false;
			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
					.find('>ul').hide().css('visibility','hidden');
			o.onHide.call($ul);
			return this;
		},
		showSuperfishUl : function(){
			var o = sf.op,
				sh = sf.c.shadowClass+'-off',
				$ul = this.addClass(o.hoverClass)
					.find('>ul:hidden').css('visibility','visible');
			sf.IE7fix.call($ul);
			o.onBeforeShow.call($ul);
			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
			return this;
		}
	});

})(jQuery);



/*
 * Supersubs v0.2b - jQuery plugin
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 *
 * This plugin automatically adjusts submenu widths of suckerfish-style menus to that of
 * their longest list item children. If you use this, please expect bugs and report them
 * to the jQuery Google Group with the word 'Superfish' in the subject line.
 *
 */

;(function($){ // $ will refer to jQuery within this closure

	$.fn.supersubs = function(options){
		var opts = $.extend({}, $.fn.supersubs.defaults, options);
		// return original object to support chaining
		return this.each(function() {
			// cache selections
			var $$ = $(this);
			// support metadata
			var o = $.meta ? $.extend({}, opts, $$.data()) : opts;
			// get the font size of menu.
			// .css('fontSize') returns various results cross-browser, so measure an em dash instead
			var fontsize = $('<li id="menu-fontsize">&#8212;</li>').css({
				'padding' : 0,
				'position' : 'absolute',
				'top' : '-999em',
				'width' : 'auto'
			}).appendTo($$).width(); //clientWidth is faster, but was incorrect here
			// remove em dash
			$('#menu-fontsize').remove();
			// cache all ul elements
			$ULs = $$.find('ul');
			// loop through each ul in menu
			$ULs.each(function(i) {	
				// cache this ul
				var $ul = $ULs.eq(i);
				// get all (li) children of this ul
				var $LIs = $ul.children();
				// get all anchor grand-children
				var $As = $LIs.children('a');
				// force content to one line and save current float property
				var liFloat = $LIs.css('white-space','nowrap').css('float');
				// remove width restrictions and floats so elements remain vertically stacked
				var emWidth = $ul.add($LIs).add($As).css({
					'float' : 'none',
					'width'	: 'auto'
				})
				// this ul will now be shrink-wrapped to longest li due to position:absolute
				// so save its width as ems. Clientwidth is 2 times faster than .width() - thanks Dan Switzer
				.end().end()[0].clientWidth / fontsize;
				// add more width to ensure lines don't turn over at certain sizes in various browsers
				emWidth += o.extraWidth;
				// restrict to at least minWidth and at most maxWidth
				if (emWidth > o.maxWidth)		{ emWidth = o.maxWidth; }
				else if (emWidth < o.minWidth)	{ emWidth = o.minWidth; }
				emWidth += 'em';
				// set ul to width in ems
				$ul.css('width',emWidth);
				// restore li floats to avoid IE bugs
				// set li width to full width of this ul
				// revert white-space to normal
				$LIs.css({
					'float' : liFloat,
					'width' : '100%',
					'white-space' : 'normal'
				})
				// update offset position of descendant ul to reflect new width of parent
				.each(function(){
					var $childUl = $('>ul',this);
					var offsetDirection = $childUl.css('left')!==undefined ? 'left' : 'right';
					$childUl.css(offsetDirection,emWidth);
				});
			});
			
		});
	};
	// expose defaults
	$.fn.supersubs.defaults = {
		minWidth		: 9,		// requires em unit.
		maxWidth		: 25,		// requires em unit.
		extraWidth		: 0			// extra width can ensure lines don't sometimes turn over due to slight browser differences in how they round-off values
	};
	
})(jQuery); // plugin code ends


    $(document).ready(function(){ 
        $("ul.sf-menu").supersubs({ 
            minWidth:    12,   // minimum width of sub-menus in em units 
            maxWidth:    27,   // maximum width of sub-menus in em units 
            extraWidth:  1     // extra width can ensure lines don't sometimes turn over 
                               // due to slight rounding differences and font-family 
        }).superfish();  // call supersubs first, then superfish, so that subs are 
                         // not display:none when measuring. Call before initialising 
                         // containing tabs for same reason. 
    });

function doShowCreateTour() {
  var memxy=mousexy;
  $.blockUI({message:'<img src="images/wait_gr.gif" border="0"/>'});
  $.post('?',{jajax:"mf_show_create_tour"},function(xml) {
      $.unblockUI();
      $("#id_create_tour_html").html($("html",xml).text());
      left=20;
      $("#id_create_tour").animate({
          left: left, top:memxy.y+10, width:700, height:400, opacity: 'show'
      }, 1000);
  });
}

function hideCreateTour() {
   $("#id_create_tour").animate({
       left: 0, top:0, width:0, height:0, opacity: 'hide'
    }, 500, '', function() {$("#id_create_tour_html").html('');});
  $('input#_st_mess').focus();
}

function doCreateTour() {
  $.blockUI({message:'<img src="images/wait_gr.gif" border="0"/>'});
  $.post('?',{jajax:"mf_create_tour",_st_dt_begin:$('input#dt_begin').val(),_st_dt_end:$('input#dt_end').val(),
                 _st_tour_access:$('textarea#tour_access').val(), _st_tour_name:escape($('input#tour_name').val()), _i_id_skin:$('select#id_skin').val(),
                 _st_tour_desc:escape($('textarea#tour_desc').val())},function(xml) {
     $.unblockUI();
     html=$("html",xml).text();
     if (html=='ok') {
        hideCreateTour();
     } else {
        alert(html);  
     }
  });
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function pagesList_jquery(js_var,obj, sp, pages, on_page, js_dosp, class_pass, class_curr, class_next) {
	 this.js_var = js_var;
	 this.obj=obj;
	 this.pages = pages-1;
	 this.on_page = on_page;
	 this.js_dosp = js_dosp;
	 this.class_pass = class_pass;
	 this.class_curr = class_curr;
	 this.class_next = class_next;
	 this.from = 0;
	 if ($.browser.msie) {
	 	 this.s_left='&lt;';
	 	 this.s_right='&gt;';
	 } else {
	 	 this.s_left='&#9001;';
	 	 this.s_right='&#9002;';
	 }
	 
	 this.sp = sp;
	 
	 this.calcFrom = function() {
	 	 this.from=this.sp-Math.round(this.on_page/2)+1;
	 	 if (this.from<0) this.from=0;
	 	 if (this.from>this.pages) this.from=0;
	 }
	
	 this.init = function() {
	 	 this.calcFrom();
	 	 s='<table cellpadding="0" cellspacing="0"><tr>';
	 	 i=0;
	 	 if (this.pages<this.on_page) {to=this.pages;} else {to=this.on_page;}
                 if (this.sp>0) {
                   s+='<td><div id="'+(this.obj+'_prev')+'" class="'+this.class_pass+'" onclick="'+this.js_var+'.onSP(this);" sp="'+(this.sp-1)+'">назад</div></td>';
                 } 
        	 s+='<td><div id="'+(this.obj+'_pg_beg')+'" class="'+this.class_pass+'" onclick="'+this.js_var+'.draw(-'+this.pages+');">'+this.s_left+this.s_left+this.s_left+'</div></td>';
  	         s+='<td><div id="'+(this.obj+'_pg_up')+'" class="'+this.class_pass+'" onclick="'+this.js_var+'.draw(-'+this.on_page+');">'+this.s_left+this.s_left+'</div></td>';
                 s+='<td><div id="'+(this.obj+'_pg_l_curr')+'" class="'+this.class_curr+'">'+(this.sp+1)+'</div></td>';
         	 s+='<td><div id="'+(this.obj+'_pg_prev')+'" class="'+this.class_pass+'" onclick="'+this.js_var+'.draw(-1);">'+this.s_left+'</div></td>';
	 	 while (i<=to) {
	 	 	  s+='<td><div id="'+(this.obj+'_pg_'+i)+'" class="" onclick="'+this.js_var+'.onSP(this);" sp=""></div></td>';
	 	 	  i++;
	 	 }
	         s+='<td><div id="'+(this.obj+'_pg_next')+'" class="'+this.class_pass+'" onclick="'+this.js_var+'.draw(1);">'+this.s_right+'</div></td>';
                 s+='<td><div id="'+(this.obj+'_pg_r_curr')+'" class="'+this.class_curr+'">'+(this.sp+1)+'</div></td>';
                 s+='<td><div id="'+(this.obj+'_pg_dn')+'" class="'+this.class_pass+'" onclick="'+this.js_var+'.draw('+this.on_page+');">'+this.s_right+this.s_right+'</div></td>';
                 s+='<td><div id="'+(this.obj+'_pg_end')+'" class="'+this.class_pass+'" onclick="'+this.js_var+'.draw('+(this.pages-this.on_page+1)+');">'+this.s_right+this.s_right+this.s_right+'</div></td>';
                 if (this.sp<this.pages) {
                    s+='<td><div id="'+(this.obj+'_next')+'" class="'+this.class_pass+'" onclick="'+this.js_var+'.onSP(this);" sp="'+(this.sp+1)+'">вперед</div></td>';
                 }
	 	 s+='</tr><table>';
	 	 $('#'+this.obj).html(s);
	 }
	 
	 this.onSP = function(th) {
	 	 sp=parseInt($(th).attr('sp'));
	 	 if (sp!=this.sp) {
	 	 	 js=this.js_dosp;
	 	 	 js=js.replace(/%sp/,sp);
	 	 	 this.sp=sp;
	 	 	 this.init();
                 	 this.draw(0, true);
	 	 	 eval(js);
	 	 }
	 }
	 
	 this.draw = function(d, force) {
	 	 f_mem=this.from;
	 	 this.from+=d;
	 	 if (this.from<0) this.from=0;
	 	 to=this.from+this.on_page-1;
	 	 if (to>this.pages) to=this.pages;
	 	 from=to-this.on_page+1;
	 	 if (from<0) from=0;
	 	 this.from = from;
	 	 if (f_mem==this.from && !force) return false;
	 	 i=0;
	 	 if (this.from>0) {$('#'+this.obj+'_pg_up').show();} else {$('#'+this.obj+'_pg_up').hide();}
	 	 if (this.from>0) {$('#'+this.obj+'_pg_prev').show();} else {$('#'+this.obj+'_pg_prev').hide();}
	 	 if (this.from-this.on_page>0) {$('#'+this.obj+'_pg_beg').show();} else {$('#'+this.obj+'_pg_beg').hide();}
	 	 while (from<=to) {
 	 	   if (from!=sp) {cl=this.class_pass;} else {cl=this.class_curr;}
	 	 	 $('#'+this.obj+'_pg_'+i).html((from+1)+'');
                         $('#'+this.obj+'_pg_'+i).removeClass(this.class_pass);
                         $('#'+this.obj+'_pg_'+i).removeClass(this.class_curr);
                         $('#'+this.obj+'_pg_'+i).addClass(cl);
                         $('#'+this.obj+'_pg_'+i).attr('sp',from);
                         $('#'+this.obj+'_pg_'+i).fadeIn(300);
	 	 	 from++;
	 	 	 i++;
	 	 }
	 	 if (from-1<this.pages) {$('#'+this.obj+'_pg_next').show();} else {$('#'+this.obj+'_pg_next').hide();}
	 	 if (from-1<this.pages) {$('#'+this.obj+'_pg_dn').show();} else {$('#'+this.obj+'_pg_dn').hide();}
	 	 if (from-1+this.on_page<=this.pages) {$('#'+this.obj+'_pg_end').show();} else {$('#'+this.obj+'_pg_end').hide();}
	 	 if (this.sp>=this.from && this.sp<from) {
	 	 	 $('#'+this.obj+'_pg_r_curr').hide();
 	 	   $('#'+this.obj+'_pg_l_curr').hide();
	 	 } else {
	 	 	 if (this.sp<this.from) {
	 	 	   $('#'+this.obj+'_pg_l_curr').show();
	 	 	   $('#'+this.obj+'_pg_r_curr').hide();
	 	 	 } else {
	 	 	   $('#'+this.obj+'_pg_r_curr').show();
	 	 	   $('#'+this.obj+'_pg_l_curr').hide();
	 	 	 }
	 	 }
	 }
	 
	 this.init();
	 this.draw(0, true);
}

var fl_check_notify = true;
var fl_blink_notify = false;
var id_notify = -1;
var mem_title='';
var prev_title='';
var _tec_mail='mail_cl2cl_all';
var _cou_unread=0;
var to_blink;

function doMailView(j, sp, f_cl, f_mess) {
  if (j!='') {_tec_mail=j;} else {j=_tec_mail;}
  if (typeof(f_cl)=='undefined') f_cl=-1;
  if (typeof(f_mess)=='undefined') f_mess=-1;
  if (!sp) sp=0;
  f_mess=escape(f_mess);
  window.scrollTo(0,0); 
  $('div#id_body').html('');
  $.blockUI({message:'<img src="images/wait_gr.gif" border="0"/>'});
  $.post('?',{jajax:j, _i_sp:sp, _i_f_cl:f_cl,_st_f_mess:f_mess},
     function(xml) {
        $.unblockUI();
        window.scrollTo(0,0); 
        $('div#id_body').html($("html",xml).text());
     }
  );
}

function doMailCl2Cl(id, id_p) {
  var memxy=mousexy;
  if (!id_p) id_p=0;
  $.blockUI({message:'<img src="images/wait_gr.gif" border="0"/>'});
  $.post('?',{jajax:"mail_cl2cl_reply",_i_id:id,_i_id_p:id_p},
     function(xml) {  
         login=$("html",xml).text();
         $.unblockUI();
         if (login!='') {
             $('#id_mail_login').html(login);
             $('textarea#id_mail_mess').val($("mess_quote",xml).text());
             $('textarea#id_mail_mess').css({height:150});
             $('textarea#id_mail_mess').Autoexpand([0,300]);
             if (memxy.x+450<$(window).width()) {x=memxy.x-50;} else {x=memxy.x-450;} if (x<10) {x=10;}
             if (memxy.y+150<$(window).height()) {y=memxy.y+5;} else {y=memxy.y-150;}
             $('div#id_mail').css({top:y, left:x});
             $('div#id_mail').slideDown('slow',function() {$('textarea#id_mail_mess').focus();});
         } 
     }
  );
}

function doMailSend() {
   login=$('#id_mail_login').html();
   mess=escape($('textarea#id_mail_mess').val());
   if (login!='') {
      $.blockUI({message:'<img src="images/wait_gr.gif" border="0"/>'});
      $.post('?',{jajax:"mail_cl2cl_send",_st_to_login:login,_st_mess:mess},
          function(xml) {  
              $.unblockUI();
              if ($("html",xml).text()=='ok') {
//                   alert('Ваше сообщение успешно доставлено адресату');
                   doNotifyClose(id_notify);
                   doMailClose();
              } else {
                   alert('Ошибка доставки сообщения. Возможно отсутствует текст?');
              }  
          }
      );
   }
}

function doMailClose() {
   $('div#id_mail').slideUp('slow');
   $('#id_mail_login').html('');
   id_notify=-1;
}

function doNotifyClose(id_n) {
   if (id_n>0) {
   $.blockUI({message:'<img src="images/wait_gr.gif" border="0"/>'});
   $.post('?',{jajax:"mail_cl2cl_set_read",id:id_n},
     function(xml) {  
        $.unblockUI();
         html=$("html",xml).text();
         if (html=='ok') {
            $('#id_notify').slideUp('slow');
            $('#id_notify').html(''); 
            fl_check_notify=true;
            id_notify=-1;
//            document.title=mem_title;
            _cou_unread--;
            if (_cou_unread==0) {
               fl_blink_notify=false;
               document.title=mem_title;
               clearTimeout(to_blink);
            }
            checkMailIN();
         }
     }
  );
  }
}

function doMailCl2Clnotify(id_from, id_n) {
   id_notify=id_n;
   doMailCl2Cl(id_from, id_n);
}

function titleBlinkNotify() {
  if (fl_blink_notify) {
     s1='/// ВАМ СООБЩЕНИЕ /// ';     s2='--- ВАМ СООБЩЕНИЕ --- ';     s3='\\\\\\ ВАМ СООБЩЕНИЕ \\\\\ ';
     if (prev_title==s1+mem_title) {
        prev_title=s2+mem_title; 
     } else {
        if (prev_title==s2+mem_title) {
           prev_title=s3+mem_title; 
        } else {
           prev_title=s1+mem_title;
        } 
     }
     document.title=prev_title;
     to_blink=setTimeout('titleBlinkNotify();',800);  
  }
}

function checkMailIN() {
   $.post('?',{jajax:"mail_cl2cl_check"},
     function(xml) {  
         if ($("_jajax",xml).text()=='ok') {
           html=$("html",xml).text();
           if (html!='') {
//                if ($.browser.msie) {
                   $('div#id_notify').css({width:'50%'});
//                }
               $('#id_notify').html(html); 
               $('#id_notify').slideDown('slow');
               fl_check_notify=false;
               $('div#id_bt_notify_reply').html('<input type="button" value="ОТВЕТИТЬ" onclick="doMailCl2Clnotify('+$("id_from",xml).text()+','+$("id_mess",xml).text()+');"/>'); 
               $('div#id_bt_notify_close').html('<input type="button" value="ЗАКРЫТЬ" onclick="doNotifyClose('+$("id_mess",xml).text()+');"/>'); 
               fl_blink_notify=true;
               cou=parseInt($("cou_unread",xml).text());
               if (_cou_unread==0) {
                  mem_title=document.title;
                  titleBlinkNotify();
               }
//_debug(_cou_unread+' '+cou+' ');
               playNotify(cou);
            } else {
               $('#id_notify').slideUp('slow');
               $('#id_notify').html(''); 
               fl_check_notify=true;
            }
        }
     }
  );
}

function checkMailINExtDraw(html, id_from, id_mess, cou_unread) {
           if (html!='') {
               $('div#id_notify').css({width:'50%'});
               $('#id_notify').html(html); 
               $('#id_notify').slideDown('slow');
               fl_check_notify=false;
               $('div#id_bt_notify_reply').html('<input type="button" value="ОТВЕТИТЬ" onclick="doMailCl2Clnotify('+id_from+','+id_mess+');"/>'); 
               $('div#id_bt_notify_close').html('<input type="button" value="ЗАКРЫТЬ" onclick="doNotifyClose('+id_mess+');"/>'); 
               fl_blink_notify=true;
               cou=parseInt(cou_unread);
               if (_cou_unread==0) {
                  mem_title=document.title;
                  titleBlinkNotify();
               }
               playNotify(cou);
            } else {
               $('#id_notify').slideUp('slow');
               $('#id_notify').html(''); 
               fl_check_notify=true;
            }
}


function checkMailINTimeOut() {
   if (fl_check_notify) checkMailIN();
   setTimeout('checkMailINTimeOut();',5000);  
}

function checkMailINCount() {
   $.post('?',{jajax:"mail_cl2cl_check_count"},
     function(xml) {  
         html=$("html",xml).text();
         if (html!='') {
            $('#id_notify_count').html(html); 
            $('#id_notify_count').slideDown('slow');
            playNotify($("cou_unread",xml).text());
         }
     }
  );
}

function checkMailINCountTimeOut() {
   if (!fl_check_notify) checkMailINCount();
   setTimeout('checkMailINCountTimeOut();',3000);  
}



function doMailFilterClient() {
   var memxy=mousexy;
   $.blockUI({message:'<img src="images/wait_gr.gif" border="0"/>'});
   $.post('?',{jajax:"mail_cl2cl_f_cl"},
     function(xml) {  
        $.unblockUI();
         html=$("html",xml).text();
         if (html!='') {
            $('div#id_mail_filter').css({top:memxy.y+5, left:memxy.x+5});
            $('div#id_mail_filter').html(html); 
            $('div#id_mail_filter').slideDown('slow');
         }
     }
  );
}

function doMailFilterClientSel(idcl) {
  doMailView('',0,idcl);
  $('div#id_mail_filter').slideUp('slow');
}

function doMailFilterMess() {
  f_mess=$('input#id_mail_f_mess').val();
  doMailView('',0,-1,f_mess);
}


function _doMailFMKU() {
   $('img#id_img_mfm_alert').show(); 
}

function playNotify(cou) {
//$('#id_debug').html(_cou_unread+' : :  '+cou); 
   if (_cou_unread!=cou) {
      $('div#id_mail_notify_wma').html('<a id="id_media_mn" class="media" href="images/mail_notify.wma"></a>');
      $('a#id_media_mn').media({autoplay: true, width:0, height:0});
   }
   _cou_unread=cou;
 }

/**
 * Interface Elements for jQuery
 * Expander
 * 
 * http://interface.eyecon.ro
 * 
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt) 
 * and GPL (GPL-LICENSE.txt) licenses.
 *   
 *
 */
 
/**
 * Expands text and textarea elements while new characters are typed to the a miximum width
 *
 * @name Expander
 * @description Expands text and textarea elements while new characters are typed to the a miximum width
 * @param Mixed limit integer if only expands in width, array if expands in width and height
 * @type jQuery
 * @cat Plugins/Interface
 * @author Stefan Petre
 */

jQuery.iExpander =
{
	helper : null,
	expand : function()
	{
		
		text = this.value;
		if (!text || (parseInt(this.style.height)==this.Expander.limit[1]))
			return;
		style = {
			fontFamily: jQuery(this).css('fontFamily')||'',
			fontSize: jQuery(this).css('fontSize')||'',
			fontWeight: jQuery(this).css('fontWeight')||'',
			fontStyle: jQuery(this).css('fontStyle')||'',
			fontStretch: jQuery(this).css('fontStretch')||'',
			fontVariant: jQuery(this).css('fontVariant')||'',
			letterSpacing: jQuery(this).css('letterSpacing')||'',
			wordSpacing: jQuery(this).css('wordSpacing')||''
		};
		jQuery.iExpander.helper.css(style);
		html = jQuery.iExpander.htmlEntities(text);
		html = html.replace(new RegExp( "\\n", "g" ), "<br />");
		jQuery.iExpander.helper.html('pW');
		spacer = jQuery.iExpander.helper.get(0).offsetWidth;
		jQuery.iExpander.helper.html(html);
		width = jQuery.iExpander.helper.get(0).offsetWidth + spacer;
		if (this.Expander.limit && width > this.Expander.limit[0]) {
			width = this.Expander.limit[0];
		}
                if (this.Expander.limit[0]>0) { 
  		   this.style.width = width + 'px';
                }
		if (this.tagName == 'TEXTAREA') {
                    height = jQuery.iExpander.helper.get(0).offsetHeight + spacer;
                    if (this.Expander.h_start<height) {  
			if (this.Expander.limit && height > this.Expander.limit[1]) {
				height = this.Expander.limit[1];
			}
			this.style.height = height + 'px';
                    }
		}
	},
	htmlEntities : function(text)
	{ 
		entities = {
			'&':'&amp;',
			'<':'&lt;',
			'>':'&gt;',
			'"':'&quot;'
		};
		for(i in entities) {
			text = text.replace(new RegExp(i,'g'),entities[i]);
		}
		return text;
	},
	build : function(limit)
	{
		if (jQuery.iExpander.helper == null) {
			jQuery('body', document).append('<div id="expanderHelper" style="position: absolute; top: 0; left: 0; visibility: hidden;"></div>');
			jQuery.iExpander.helper = jQuery('#expanderHelper');
		}
		return this.each(
			function()
			{
				if (/TEXTAREA|INPUT/.test(this.tagName)) {
					if (this.tagName == 'INPUT') {
						elType = this.getAttribute('type');
						if (!/text|password/.test(elType)) {
							return;
						}
					}
                                        h_start=0;
					if (this.tagName == 'TEXTAREA') {
                                           if (this.style.height) { 
                                             h_start=parseInt(this.style.height);
                                           } else {
                                             h_start=200; this.style.height = h_start+'px';
                                           }
                                        }
					if (limit && (limit.constructor == Number || (limit.constructor == Array && limit.length == 2))) {
						if (limit.constructor == Number)
							limit = [limit, limit];
						else {
                                                        if (parseInt(limit[0])==0) {limit[0]=0;} else {limit[0] = parseInt(limit[0])||400;}
							limit[1] = parseInt(limit[1])||400;
						}
						this.Expander = {
							limit : limit,
                                                        h_start : h_start
						};
					}
					jQuery(this)
						.blur(jQuery.iExpander.expand)
						.keyup(jQuery.iExpander.expand)
						.keypress(jQuery.iExpander.expand);
					jQuery.iExpander.expand.apply(this);
				}
			}
		);			
	}
};

jQuery.fn.Autoexpand = jQuery.iExpander.build;

var last_id_chat_game = -1;
var last_redraw='';
var id_opinion_curr = -1;
var fl_gm_pr_en=true;
var fl_mess_filter=0;
var tm_total;
var tm_step;
var w_table=160;
var h_table=170;
var last_game_status=-1;
var fl_scroll_chat=true;
var fl_scroll_chat_sys=true;
var fl_scroll_chat_mem=true;
var fl_scroll_chat_now=false;
var fl_frost = 0;
var last_id_chat_scroll = -1;
var last_im_status = 0;
var prev_dn='';
var fl_stop=0;
var to_autoexit = false;
var fl_sec_autoexit = false;
var fl_run_autoexit = false;

function gmPausePlay() {
   if (confirm('Остановить/Продолжить?')) {
  $.blockUI({message:'<img src="/images/wait_gr.gif" border="0"/>'});
  $.post('?',{jajax:"gm_pp",id_game:__id_game},function(xml) {
      $.unblockUI();
      html=$("html",xml).text();
      if (html!='ok') {alert(html);}
  });
  }
}

function gmCancelResult() {
   txt=escape($('textarea#txt_cancel_result').val());
  if (confirm('Отменить результаты игры?')) {$.post('?',{jajax:"gm_cancel_result",id_game:__id_game,txt:txt},function(xml) {location.reload();});}
}

function gmShowCancelResult() {
   $("#id_cancel_result").animate({
          left: 50, top:50, opacity: 'show'
   }, 500);
}

function gmUnCancelResult() {if (confirm('Восстановить результаты игры?')) {$.post('?',{jajax:"gm_uncancel_result",id_game:__id_game},function(xml) {location.reload();});}}

function setGameLayout(layout) {
    location.href="/?redirect=mf_game="+__id_game+"&ta=set_attr&attr=game_chat_position&var="+layout+"&";
}

function sm2inp(img) {
  s=img.src; ar=s.split('/'); s=ar[ar.length-1]; ar=s.split('.'); sm=ar[0];
  v=$('input#_st_mess').val();
  $('input#_st_mess').val(v+' :'+sm+': ');
  closeSmileStreet();
  $('input#_st_mess').focus();
}

function showSmilesGame() {
   memxy=mousexy;
   $("#id_smiles_street").animate({left: memxy.x-200, top:$(window).height()-250, opacity: 'show'}, 500);
}

function _h_table(hset) {
  if (hset) {$('.gm-cl').height(hset); return true;}
  h_table=170;
  $('.gm-cl').each(
     function() {
        h=$('#'+this.id).height(); 
        if (jQuery.browser.mozilla && jQuery.browser.version.substr(0,3)=="1.8") {h-=10;}
        h_table=Math.max(h_table,h);
     }  
  )
  $('.gm-cl').height(h_table+1);
}


function doShowMessChat(tp) {
   if (fl_mess_filter!=tp) {
     switch (tp) {
       case 0: $('tr[fl_sys=1]').show();   $('tr[fl_sys=0]').show();   break;
       case 1: $('tr[fl_sys=0]').show();   $('tr[fl_sys=1]').hide();   break;
       case 2: $('tr[fl_sys=0]').hide();   $('tr[fl_sys=1]').show();   break;
     }
     if (fl_scroll_chat) {
        $('#id_game_chat').attr('scrollTop',$('#id_game_chat').attr('scrollHeight'));
     }
   }
   fl_mess_filter=tp;
}

function showOpinion(id) {
  id_opinion_curr=id;
  memxy=mousexy;
  $('#id_opinion').css({top:memxy.y+10, left:memxy.x-50});
  $('#id_opinion').slideDown();
}

function hideOpinion() {$("#id_opinion").hide(); id_opinion_curr=-1;}

function doSetOpinion(t,clear) {
  if (clear) {opinion='';} else {opinion=$(t).html();}
  opinion2=escape(opinion);
  if (opinion=='') opinion='мнение';
  $('#id_op_'+id_opinion_curr).html('{'+opinion+'}');
  $.post('?',{jajax:"mf_set_opinion",_i_id_game:__id_game,_i_id_about:id_opinion_curr,_s_opinion:opinion2},function(xml) {
  });
  hideOpinion();
  $('input#_st_mess').focus();
}

function doGameMess(e,v) {
  var keynum;
  var keychar;

  if(window.event) {keynum = e.keyCode;} else if(e.which) {keynum = e.which;}
  keychar = String.fromCharCode(keynum);

  v=v.replace(/^s*/, "").replace(/s*$/, "");
  if (keynum==13 && v!='') {
	  $('input#_st_mess').val('');
          if (v=='') return false;
          v=escape(v);
          $.post('?',{jajax:"mf_sendchatmess",_s_mess:v,_i_id_game:__id_game},function(xml) {
        	  html_game_redraw();
                  if (fl_mess_filter==2) $('input#rb_cm_0').click();
          });
          return true;
  }
  if (keynum==27) {
     hideSendPrivate();
     $('input#_st_mess').val('');
  }
  return false;
}

function _draw_time(tm) {
  tm=tm.split('|');
  for (i=0; i<tm.length; i++) {tm[0]=parseInt(tm[0]);  tm[1]=parseInt(tm[1]);  tm[2]=parseInt(tm[2]);}
  if (fl_stop==1) {tm_total.stop(); tm_step.stop();} else {if (tm[0]<100) {tm_total.setSec(tm[1]); tm_step.setSec(tm[2]);}}
}

function _draw_clients(im,scl,gs,fl_play) {
  if (gs=='') return false;

  im=im.split('|');  for (i=0; i<im.length; i++) { if (i!=8) {im[i]=parseInt(im[i]);}}
  last_im_status=im[2];

  gs=gs.split('|');
  for (i=0; i<gs.length; i++) {
     gs[0]=parseInt(gs[0]);  gs[2]=parseInt(gs[2]);  gs[3]=parseInt(gs[3]);  gs[4]=parseInt(gs[4]);  gs[5]=parseInt(gs[5]); gs[11]=parseInt(gs[11]); gs[12]=parseInt(gs[12]);  gs[13]=parseInt(gs[13]);  gs[14]=parseInt(gs[14]); 
     gs[15]=parseInt(gs[15]); gs[16]=parseInt(gs[16]); gs[17]=parseInt(gs[17]);  gs[18]=parseInt(gs[18]); gs[25]=parseInt(gs[25]);  gs[38]=parseInt(gs[38]);  gs[39]=parseInt(gs[39]);  gs[40]=parseInt(gs[40]);  gs[41]=parseInt(gs[41]); gs[43]=parseInt(gs[43]);
     gs[44]=parseInt(gs[44]);   gs[45]=parseInt(gs[45]);
  }

  step=gs[11];
  $('#id_step').html(gs[1]+', ');
  if (gs[0]>99) {
    $('#id_game_status').html(gs[10]+', ');
  }

  dn=gs[0]+'|'+gs[38];
  if (dn!=prev_dn && __game_status<100) {
      drawDayNightHistory(gs[0],gs[38]);
     _h_table();
  }
  prev_dn=dn;

  if (gs[25]==1 || gs[0]>99) {
    $('#id_siskins').html(gs[27]+': '+gs[9]+' из '+gs[8]);
    $('#id_mafs').html(', '+gs[26]+': '+gs[7]+' из '+gs[6]);
  } else {
    $('#id_siskins').html(gs[27]+': '+gs[8]);
    $('#id_mafs').html(', '+gs[26]+': '+gs[6]);
  }

  if (gs[12]==2) {
     $('#id_add_options').html('голосование - обязательно, '); 
  }

  if (gs[31]!='') gs[31]=' '+gs[31];   if (gs[30]!='') gs[30]=' '+gs[30];   if (gs[28]!='') gs[28]=' '+gs[28];   if (gs[29]!='') gs[29]=' '+gs[29];   if (gs[32]!='') gs[32]=' '+gs[32]; 
  if (gs[33]!='') gs[33]=' '+gs[33]; 
  if (gs[17]>=0) {$('#id_boss_status').html(', '+gs[20]+gs[31]);} 
  if (gs[16]>=0) {$('#id_vsb_status').html(', '+gs[21]+gs[30]);}
  if (gs[3]>=0) {$('#id_kom_status').html(', '+gs[22]+gs[28]);}
  if (gs[4]>=0) {$('#id_serg_status').html(', '+gs[23]+gs[29]);}
  if (gs[5]>=0) {$('#id_doc_status').html(', '+gs[19]+gs[32]);}
  if (gs[15]>=0) {$('#id_maniac_status').html(', '+gs[24]+gs[33]);}

  if (gs[41]==1) {
     $('#id_stake_options').html('игра со ставкой '+gs[42]+', ');
  }

  if (im[10]==0 || im[13]==1) {
       $('#id_div_mess_all').hide();
       $('.mess-to').hide();
  } else {
       $('#id_div_mess_all').show();
  }

  if (scl=='') return false;

  $('#top_status').removeClass('color-day').removeClass('color-night');
  $('#_st_mess').removeClass('bg-color-day').removeClass('bg-color-night');
  switch (gs[0]) {
     case 2: if (last_game_status!=2) {$('#id_handshake').animate({opacity:'show'},1500); if (fl_play) {$("table[fl_bolvan=1]").hide();}} break;
     case 3: if (last_game_status==2) {$('#id_handshake').animate({opacity:'hide'},1500);} if (last_game_status!=3) {$('#id_night').animate({opacity:'hide'},1500,0,function() {$('#id_day').animate({opacity:'show'},1500);}); if (fl_play) {$("table[fl_bolvan=1]").hide();}} $('#top_status').addClass('color-day'); $('#_st_mess').addClass('bg-color-day'); break;
     case 4: if (last_game_status!=4) {$('#id_day').animate({opacity:'hide'},1500,0,function() { $('#id_night').animate({opacity:'show'},1500);}); if (fl_play) {$("table[fl_bolvan=1]").hide();}} $('#top_status').addClass('color-night'); $('#_st_mess').addClass('bg-color-night'); break;
     case 5: if (last_game_status!=5) {$('#id_day').hide(); $('#id_night').hide(); $('#id_duel').animate({opacity:'show'},1500); if (fl_play) {$("table[fl_bolvan=1]").show();}}  
                 if (im[13]==0 && im[2]==0) {$('#id_fl_duel').show();} else {$('#id_fl_duel_v').show();}
     break;
     default: $('#id_day').hide(); $('#id_night').hide(); $('#id_duel').hide(); $('#id_fl_duel').hide(); $('#id_fl_duel_v').hide(); $('table#id_tbl_field').removeClass(); break;
  }

  last_game_status=gs[0];
  fl_stop=gs[39];
  if (fl_stop==1) {$('#id_fl_stop').show();} else {$('#id_fl_stop').hide();}

  ar=scl.split('|');
  for (i=0; i<ar.length; i++) {
     p=ar[i].split(':');
     p[0]=parseInt(p[0]); p[1]=parseInt(p[1]); p[2]=parseInt(p[2]); p[4]=parseInt(p[4]); p[8]=parseInt(p[8]); p[6]=parseInt(p[6]); p[9]=parseInt(p[9]); p[13]=parseInt(p[13]); p[10]=parseInt(p[10]); 


     $('#id_cou_prison_'+p[0]).html('');
     $('#id_td_pr_'+p[0]).removeClass('pr-active');
//     $('#id_prison_det_'+p[0]).html('');
     $('#id_prison_login_'+p[0]).html('');

     if (gs[0]==3 || gs[0]==5) {

        if ((p[9]>0 || p[7]!='') && gs[0]<100) {
          if (p[9]>0) {
            $('#id_cou_prison_'+p[0]).html('голосов: <b>'+p[9]+'</b>');
            if (p[9]>5) {fs=5;} else {fs=p[9];} fs=fs*2+9;
            $('#id_cou_prison_'+p[0]).css({'font-size':fs});
            arl=p[14].split(';'); ls='';
//            for (l=0; l<arl.length; l++) {if (ls!='') ls+=', '; ls+='<a class="pr-login" href="javascript:viewSendPrivate(''+arl[l]+'');">'+arl[l]+'</a>';}  $('#id_prison_det_'+p[0]).html(ls);
            for (l=0; l<arl.length; l++) {if (ls!='') ls+=', '; ls+=arl[l];}  $('#id_cou_prison_'+p[0]).attr('title',ls);
          } 
          if (p[7]!='') {$('#id_prison_login_'+p[0]).html('против: '+p[7]);}
          $('#id_td_pr_'+p[0]).addClass('pr-active');
        } 
     }


    if (gs[0]==4) {
       _h_table(170);
        if (p[6]>0) {
            $('#id_cou_prison_'+p[0]).html('голосов: '+p[6]+'');
            $('#id_td_pr_'+p[0]).addClass('pr-active');
        } else {
             $('#id_td_pr_'+p[0]).removeClass('pr-active');
        } 
    }

    if (p[2]>=0) {
      $('#id_role_'+p[0]).html(p[3]);
    } else {
       if (p[0]==__id_client) {
          $('#id_role_'+p[0]).html(im[8]);
       } else {
          $('#id_role_'+p[0]).html('');
       }
    }

     if (gs[0]>100 && gs[43]==0  && gs[41]>0) {
         if (p[11]>0) {
             $('#id_sm_win_'+p[0]).html('выигрыш: '+p[11]+'');
         } else if (p[11]<0) {
             $('#id_sm_los_'+p[0]).html('проигрыш: '+p[11]+'');
         } else if (p[11]==0) {
             $('#id_sm_step0_'+p[0]).html('выбыл на 1-м этапе');
         } 
     }

     old_class=$('table#id_gamer_'+p[0]).attr('class');
     if (old_class) {
       old_class=old_class.replace(/gm-cl/,''); old_class=old_class.replace(/^s*/, "").replace(/s*$/, "");
     }
//_debug(old_class);

     tbl_class='gamer';
    
     if (p[1]==6 || p[1]==1 || p[1]==2 || p[1]==3) {
        $('#id_op_'+p[0]).hide(); $('#id_do_'+p[0]).hide();  $('#id_role_'+p[0]).removeClass(); $('#id_role_'+p[0]).addClass('role-end');
     }
     if ((im[0]==2 || im[0]==3) && (p[2]==2 || p[2]==3)) {tbl_class='police';}
     if (im[0]==1 && p[2]==1) {tbl_class='maf';}

     fl_kill = false;  fl_suicide = false;
     switch (p[1]) {
        case 6:
          $('#id_status_img_'+p[0]).html('<img src="?imgivw=gm_suicide" align="left"/>');
          $('#id_status_text_'+p[0]).html(gs[37]);
          tbl_class='suicide';
          fl_suicide = true;
        break; 
        case 1:
          if (p[5]=='man' || (gs[45]==1 && p[0]!=__id_client && gs[0]<100)) {$('#id_status_img_'+p[0]).html('<img src="?imgivw=man_prison" align="left"/>');} else {$('#id_status_img_'+p[0]).html('<img src="?imgivw=woman_prison" align="left"/>');}
          $('#id_status_text_'+p[0]).html(gs[34]);
          tbl_class='prison';
          fl_kill = true;
        break; 
        case 2:
          if (p[5]=='man' || (gs[45]==1 && p[0]!=__id_client && gs[0]<100)) {$('#id_status_img_'+p[0]).html('<img src="?imgivw=man_kill" align="left"/>');} else {$('#id_status_img_'+p[0]).html('<img src="?imgivw=woman_kill" align="left"/>');}
          $('#id_status_text_'+p[0]).html(gs[35]);
          tbl_class='kill';
          fl_kill = true;
        break; 
        case 3:
          if (p[5]=='man' || (gs[45]==1 && p[0]!=__id_client && gs[0]<100)) {$('#id_status_img_'+p[0]).html('<img src="?imgivw=man_kill" align="left"/>');} else {$('#id_status_img_'+p[0]).html('<img src="?imgivw=woman_kill" align="left"/>');}
          $('#id_status_text_'+p[0]).html(gs[36]);
          tbl_class='kill';
          fl_kill = true;
        break; 
        default: 
          if (p[5]=='man' || (gs[45]==1 && p[0]!=__id_client && gs[0]<100)) {$('#id_status_img_'+p[0]).html('<img src="?imgivw=gm_man" align="left"/>');} else {$('#id_status_img_'+p[0]).html('<img src="?imgivw=gm_woman" align="left"/>');}
          $('#id_status_text_'+p[0]).html('');
          tbl_class='gamer';
        break;
     }

     if (fl_kill && gs[25]==1) {if (p[5]=='man' || (gs[45]==1 && p[0]!=__id_client && gs[0]<100)) {tbl_class='gamer-man';} else {tbl_class='gamer-woman';}}

     if (im[13]==0 && gs[0]<100 && p[10]==0 && p[0]!=__id_client && im[2]==0 && ((p[13]==0 && gs[0]==5) || gs[0]!=5)) {$('#id_to_'+p[0]).show();} else {$('#id_to_'+p[0]).hide();}
     if (p[0]==__id_client || (p[2]==0 && (im[0]==2 || im[0]==3)  && p[1]==0)) {
        tbl_class='mycard';
         if (p[5]=='man' || (gs[45]==1 && p[0]!=__id_client && gs[0]<100)) {tbl_class='gamer-man';} else {tbl_class='gamer-woman';}
     }
     if ((p[0]==__id_client && im[13]==1) || p[13]==1) {
          if (gs[0]==5) {tbl_class='duel-hide';} else {tbl_class='frost';}
          $('#id_status_text_'+p[0]).html(__s_frost);
     } else {
         if (gs[0]>99 && p[2]==0) {
               if (p[5]=='man' || (gs[45]==1 && p[0]!=__id_client && gs[0]<100)) {tbl_class='gamer-man';} else {tbl_class='gamer-woman';}
        }
//       if ((p[0]!=__id_client && im[0]==1  && p[2]==1 && p[1]==0) || (p[2]==1 && (im[0]==2 || im[0]==3)  && p[1]==0) || (gs[0]>99 && p[2]==1 && p[1]==0)) {
       if ((im[0]==1  && p[2]==1 && p[1]==0) || (p[2]==1 && (im[0]==2 || im[0]==3)  && p[1]==0) || (gs[0]>99 && p[2]==1 && p[1]==0) || (p[2]==1 && fl_kill && (gs[25]==1 || gs[0]>99))) {
         if (p[4]==7) {
            tbl_class='boss';
         } else {
             if (p[5]=='man' || (gs[45]==1 && p[0]!=__id_client && gs[0]<100)) {tbl_class='maf-man';} else {tbl_class='maf-woman';}
          }
       }  
//       if ((p[0]!=__id_client && (im[0]==2 || im[0]==3) && (p[2]==2 || p[2]==3)  && p[1]==0)  || (gs[0]>99 && (p[2]==2 || p[2]==3) && p[1]==0)) {
       if (((im[0]==2 || im[0]==3) && (p[2]==2 || p[2]==3)  && p[1]==0)  || (gs[0]>99 && (p[2]==2 || p[2]==3) && p[1]==0) || ((p[2]==2 || p[2]==3)  && fl_kill && (gs[25]==1 || gs[0]>99))) {
//          tbl_class='police';
          if (p[2]==2) {tbl_class='kom';}
          if (p[2]==3) {tbl_class='serg';}
       }  
       if ((p[0]!=__id_client && im[0]==1 && p[2]==0 && p[4]==6  && p[1]==0)  || (gs[0]>99 && p[2]==0 && p[4]==6 && p[1]==0) || (p[2]==0 && p[4]==6 && (im[0]==2 || im[0]==3)  && p[1]==0)) {
//          tbl_class='vsb';
          if (p[5]=='man' || (gs[45]==1 && p[0]!=__id_client && gs[0]<100)) {tbl_class='vsb-man';} else {tbl_class='vsb-woman';} 
       }  
       if (p[10]==1) {
          if (gs[0]==5) {tbl_class='bolvan';} else {tbl_class='duel-hide';}
       } 
       if ((im[0]==4 && p[0]==__id_client) || (gs[0]>99 && p[2]==4 && p[1]==0) || (fl_kill &&  p[2]==4  && (gs[25]==1 || gs[0]>99)) || (p[2]==4 && (im[0]==2 || im[0]==3)  && p[1]==0)) {
//          tbl_class='doc';
           if (p[5]=='man' || (gs[45]==1 && p[0]!=__id_client && gs[0]<100)) {tbl_class='doc-man';} else {tbl_class='doc-woman';}
       }  
//       if ((p[0]!=__id_client && im[0]==1 && p[2]==5 && p[1]==0)  || (gs[0]>99 && p[2]==5 && p[1]==0)) {
       if ((p[0]==__id_client && im[0]==5 && gs[0]==4)  || (p[0]!=__id_client && im[0]==1 && p[2]==5 && p[1]==0)  || (gs[0]>99 && p[2]==5 && p[1]==0) || (p[2]==5 && fl_kill  && (gs[25]==1 || gs[0]>99)) || (p[2]==5 && (im[0]==2 || im[0]==3)  && p[1]==0)) {
          tbl_class='maniac';
       }  
       if (gs[0]==5 && (p[1]>0 || p[13]==1)) {
          tbl_class='duel-hide';
       }  

     }

     if (!fl_suicide && fl_kill && tbl_class!='duel-hide' && (gs[25]==1 || gs[0]>99)) {tbl_class+='-kill';}
     if (gs[44]==5) {tbl_class='bask-'+tbl_class;  }

     if (fl_suicide) {tbl_class='suicide';} 

//_debug(p[0]+' '+tbl_class);

     if (old_class!=tbl_class) {
        $('table#id_gamer_'+p[0]).removeClass(old_class); 
        $('table#id_gamer_'+p[0]).addClass(tbl_class);
        if (tbl_class=='duel-hide') {
            $('table#id_gamer_'+p[0]).hide();
        } else {
            $('table#id_gamer_'+p[0]).show();
        }    
        if (p[0]==__id_client) {
//             $('table#id_gamer_'+p[0]+' .bg-tl').addClass('mytitle');
//             $('table#id_gamer_'+p[0]+' .id_bt_gm').css('font-weight','bold').css('color','#00FF33').css('text-decoration','underline');
             $('table#id_gamer_'+p[0]+' .id_bt_gm').css('font-weight','bold').css('color','#FED6A1').css('text-decoration','underline');

        } 
     }

     $('table#id_gamer_'+p[0]).addClass(tbl_class);

     fl_bt=false;
     fl_bt_2=false;
   
     if ((gs[0]==3 || gs[0]==5) && p[1]==0 && im[3]==0 && im[4]==0 && im[2]==0 && im[13]==0 && gs[39]==0 && ((p[13]==0 && gs[0]==5) || gs[0]!=5)) {
        fl_bt=true;
        if (p[0]==__id_client) {
           if (gs[0]!=5) {
              $('#id_bt_do_'+p[0]).html('<img src="?imgivw=gm_skip" title="ничего не делать на этом ходу" class="bt" onclick="doSkip(this);" id="img1_'+p[0]+'"/>'); 
           }
        } else {
           $('#id_bt_do_'+p[0]).html('<img src="?imgivw=gm_prison" title="'+__title_do_send_to_prison+'" class="bt" onclick="doPrison(this,'+p[0]+');" id="img2_'+p[0]+'"/>'); 
        }
     } 

     if (gs[0]==4 && p[1]==0 && im[5]==0 && im[4]==0 && im[2]==0 && im[0]==1 && p[2]!=5 && p[4]!=6  && im[13]==0  && gs[39]==0) {
        fl_bt=true;
        if (p[0]==__id_client) {
           $('#id_bt_do_'+p[0]).html('<img src="?imgivw=gm_skip" title="ничего не делать на этом ходу" class="bt" onclick="doSkip(this);" id="img1_'+p[0]+'"/>'); 
        } else {
           $('#id_bt_do_'+p[0]).html('<img src="?imgivw=gm_kill" title="'+__title_do_kill+'" class="bt" onclick="doKill(this,'+p[0]+');" id="img2_'+p[0]+'"/>'); 
        }
     } 

     if (gs[13]>gs[14] && gs[0]==4 && p[1]==0 && p[8]==0 && im[4]==0 && im[2]==0 && im[6]==0 && p[2]!=3 && im[6]==0 && (im[0]==2 || (im[1]==2 && gs[3]!=0))  && im[13]==0 && gs[39]==0) {
        fl_bt=true;
        if (p[0]==__id_client) {
           $('#id_bt_do_'+p[0]).html('<img src="?imgivw=gm_skip" title="ничего не делать на этом ходу" class="bt" onclick="doSkip(this);" id="img1_'+p[0]+'"/>'); 
        } else {
           $('#id_bt_do_'+p[0]).html('<img src="?imgivw=gm_check" title="проверить" class="bt" onclick="doCheck(this,'+p[0]+');" id="img2_'+p[0]+'"/>'); 
        }
     } 

     if (gs[0]==4 && p[1]==0 && im[4]==0 && im[2]==0 && im[7]==0 && im[0]==4  && im[13]==0 && gs[39]==0) {
        fl_bt=true;
        if (p[0]==__id_client) {
           $('#id_bt_do_'+p[0]).html('<img src="?imgivw=gm_skip" title="ничего не делать на этом ходу" class="bt" onclick="doSkip(this);" id="img1_'+p[0]+'"/>'); 
        } else {
           $('#id_bt_do_'+p[0]).html('<img src="?imgivw=gm_doc_check" title="'+ __title_do_doc_cure+'" class="bt" onclick="doDoc(this,'+p[0]+');" id="img2_'+p[0]+'"/>'); 
        }
     }

     if (gs[0]==4 && p[1]==0 && im[4]==0 && im[2]==0 && im[11]==0 && im[0]==5 && gs[39]==0) {
        fl_bt=true;
        if (p[0]==__id_client) {
           $('#id_bt_do_'+p[0]).html('<img src="?imgivw=gm_skip" title="ничего не делать на этом ходу" class="bt" onclick="doSkip(this);" id="img1_'+p[0]+'"/>'); 
        } else {
           $('#id_bt_do_'+p[0]).html('<img src="?imgivw=gm_knife" title="напасть" class="bt" onclick="doManiac(this,'+p[0]+');" id="img2_'+p[0]+'"/>'); 
        }
     }

     if (gs[0]==4 && p[1]==0 && im[4]==0 && im[2]==0 && im[0]==1 && im[1]==7 && p[2]!=5 && p[4]!=6 && gs[18]==0 && gs[39]==0) {
        fl_bt_2=true;
        if (p[0]==__id_client) {
           $('#id_bt_do_2_'+p[0]).html('<img src="?imgivw=gm_skip_frost" title="" class="bt2" onclick="doFrost(this,-1);" id="img3_'+p[0]+'"/>'); 
        } else {
           $('#id_bt_do_2_'+p[0]).html('<img src="?imgivw=gm_frost" title="'+__title_do_frost+'" class="bt2" onclick="doFrost(this,'+p[0]+');" id="img4_'+p[0]+'"/>'); 
        }
     }

     if (!fl_bt) $('#id_bt_do_'+p[0]).html('');    $(".bt").show();
     if (!fl_bt_2) $('#id_bt_do_2_'+p[0]).html('');    $(".bt2").show();


     if (p[1]==0 && gs[0]<100 && im[2]==0 && p[0]!=__id_client  &&  (((im[6]==0 && (im[0]==2 || im[0]==3)) || (im[0]!=2 && im[0]!=3))  ||  ((im[0]==1 && p[2]!=1) || im[0]!=1))   )   {
        $('#id_op_'+p[0]).show(); 
     } else {
        $('#id_op_'+p[0]).hide(); 
     }


//     if (im[2]!=0 || gs[0]>99) {$('#id_bt_suicide').hide(); $('#id_bt_exit').show();} else {$('#id_bt_suicide').show();$('#id_bt_exit').hide();}
//     if (gs[0]>99) {$('#id_bt_switch').hide();}

     if (im[2]!=0 || gs[0]>99 || fl_stop) {$('img#bt_suicide').hide(); $('img#bt_on_street').show();}

     if (gs[0]>99) {$('li#mn_gamestop').hide();}

     if ((im[2]>0 || p[1]>0) && gs[0]<100) { 
           $('#id_login_'+p[0]).click(function() {doMailCl2Cl($(this).attr('idcl'));});
     }


     if (p[1]==0 && gs[0]<100 && im[9]==1 && im[13]==0 && p[10]==0 && p[0]!=__id_client && ((p[13]==0 && gs[0]==5) || gs[0]!=5)) {
//        login=$('id_login_'+p[0]).attr('login');  
//        $('#id_login_'+p[0]).click(function() {doMailCl2Cl($(this).attr('login'));});
        $('#id_pr_'+p[0]).show();
     } else {
//if (im[13]==1) _debug(p[0]);
        $('#id_login_'+p[0]).click(function() {});
        $('#id_pr_'+p[0]).hide();
     }
     fl_frost=im[13];

     if (im[10]==2) {
       $('input#_st_mess').css({'background-color':'#FFC2C5'});
       $('#id_last_mess').show();
     }

  }

  if (!fl_play && gs[0]>99 && __game_status<100 && __gameautoexit>0 && !fl_run_autoexit) {
        fl_sec_autoexit = true;
        fl_run_autoexit = true;
        $('#id_on_street').animate({left: 10, top:50, opacity: 'show'}, 500);
        runAutoExit();
  }

  if (!fl_play && gs[0]>99) {
       mf_game_last_click();
  }

//  _h_table();
}


function html_game_redraw() {
  if (fl_gm_pr_en && last_game_status<100) {
     fl_gm_pr_en=false;
     $.ajax({
url: "/?",
type: "POST",
data:({jajax:"mf_game_redraw",_s_id_div:'id_game_chat',id_game:__id_game,_s_tp_chat:'_chat_game',id_last:last_id_chat_game,gs:__game_status}),
dataType: "xml",
timeout: 30000,
                                       error: function(html){
                                           ping_error_count++; 
                                           if (ping_error_count>3) {
                                               $('body,table').css('cursor', 'wait'); 
                                               $('#id_ping_alert').html('Кажется, вот уже '+(__to_st_chat/1000*ping_error_count)+' секунд как пропала связь с сервером... <br>Обновить страницу? Перещёлкнуть модем? Проверить канал?'); 
                                               $('#id_ping_alert').show(); 
                                           }  
                                           fl_gm_pr_en=true;
                                       },
success: function(xml) {

                                           if (ping_error_count>0) {
                                               $('body,table').css('cursor', 'default'); 
                                               $('#id_ping_alert').hide(); 
                                           }  
                                           ping_error_count = 0;


      mess_reload=$("mess_reload",xml).text();
      if (mess_reload!='') {
        $.blockUI({message:'<span class="ui_warning">'+mess_reload+'</span>'});
        location.reload();
        return false;
      }

       fl_reload = $("fl_reload",xml).text();
       if (fl_reload=='1') {
               location.reload();
       }

       last_id_chat_game=$("id_last",xml).text();
       if ($("chat_curr",xml).text()!='') {
         $('#id_game_chat').append($("chat_curr",xml).text());
         if (fl_scroll_chat) {$('#id_game_chat').attr('scrollTop',$('#id_game_chat').attr('scrollHeight'));}
//         $(".chat-login").click( function() { _doMessClient(this);} );
       }
    
       if (__game_chat_pos=='bottom') {
          if ($("chat_curr_sys",xml).text()!='') {
            $('#id_game_chat_sys').append($("chat_curr_sys",xml).text());
            if (fl_scroll_chat_sys) {$('#id_game_chat_sys').attr('scrollTop',$('#id_game_chat_sys').attr('scrollHeight'));}
          }
       }
       im=$("im",xml).text();
       scl=$("s_clients",xml).text();

       gs=$("gs",xml).text();
       if ((im+scl+gs)!=last_redraw) {_draw_clients(im,scl,gs,false);}

       _draw_time($("tm",xml).text());

//       $('#id_game_chat').css({height:$(window).height()-190});
       last_redraw=im+scl+gs;

       $('.cl_delay').addClass('hide');  
       s_last_click =  $("s_last_click",xml).text(); 
       if (s_last_click!='') {
          ar= s_last_click.split('|');
          for (i=0; i<ar.length; i++) {
            arlc = ar[i].split(':');
            if (arlc[1]>10)  {
                $('#cl_delay_'+arlc[0]).html('нет на связи - '+arlc[1]+ ' сек');  
                $('#cl_delay_'+arlc[0]).removeClass('hide');  
            }
          } 
       } 


              html=$("mail_notify_html",xml).text();
              if (html!='') {checkMailINExtDraw(html, $("mail_notify_id_from",xml).text(), $("mail_notify_id_mess",xml).text(), $("mail_notify_cou_unread",xml).text());}


       fl_gm_pr_en=true;
}

  });
  }
}

function game_redraw() {
  html_game_redraw();
  setTimeout('game_redraw();',__to_st_chat);
}

function _doMessClient(t) {
   v=$('input#_st_mess').val();
   $('input#_st_mess').val('to['+t.innerHTML+'] '+v);
   $('input#_st_mess').focus();
}

function _doMessClientPR(t) {
   v=$('input#_st_mess').val();
   $('input#_st_mess').val('pr['+t.innerHTML+'] '+v);
   $('input#_st_mess').focus();
}

function _doPRClient(login) {
   v=$('input#_st_mess').val();
   $('input#_st_mess').val('pr['+login+'] '+v);
   $('input#_st_mess').focus();
}

function _doTOClient(login) {
   v=$('input#_st_mess').val();
   $('input#_st_mess').val('to['+login+'] '+v);
   $('input#_st_mess').focus();
}

function viewSendPrivate(login) {
  if (fl_frost==0) {
   hideSendPrivate();
    memxy=mousexy;
    $('input#pr_mess').val('pr['+login+'] ');
    $('td#pr_login').html('Приватное сообщение для: '+login);
//alert(memxy.x+' '+$(window).width());
    if (memxy.x+550>$(window).width()) {memxy.x=$(window).width()-550;}
    $("#id_private").animate({
       left: memxy.x, top:memxy.y, width:500, opacity: 'show'
     }, 200, '', function() {$('input#pr_mess').focus();});
  }
}

function hideSendPrivate() {$("#id_private").hide(); $('input#_st_mess').focus();}

function viewMessHistory(id,login) {
  memxy=mousexy;

  $('td#hs_login').html('История сообщений игрока: '+login);
  $.post('?',{jajax:"mf_htmlchat",_i_id_game:__id_game,_i_id_with:id,_s_tp_chat:'_chat_history'},function(xml) {
      $('#id_mess_history_html').html($("html",xml).text());
      x=memxy.x;
      w=Math.round($(window).width()/3);
      if (x+w+80>$(window).width()) {x=$(window).width()-w-80;}
      $("#id_mess_history_html").css({height:400,width:w});
      $("#id_mess_history").animate({
           left: x, top:memxy.y, opacity: 'show', width:w+40
       }, 200);
   });
}

function hideMessHistory() {
   $("#id_mess_history").hide();
   $('input#_st_mess').focus();
}

function nextStep() {
  $.post('?',{jajax:"mf_next_step",_i_id_game:__id_game},function(xml) {

     step=$("step",xml).text();
//     if (__step!=step) {
//        location.reload();
//     }
   });
}

function nextStepForce() {
  $.blockUI({message:'<img src="/images/wait_gr.gif" border="0"/>'});
  $.post('?',{jajax:"mf_next_step_force",_i_id_game:__id_game},function(xml) {
     $.unblockUI();
     step=$("step",xml).text();
//     if (__step!=step) {location.reload();}
   });
}


function _bt_anim(t) {
   $('img#'+t.id).animate({opacity: 0.0},200,'',function() {$('img#'+t.id).animate({opacity: 100},300);});
}

function doSkip(t) {
  _bt_anim(t);
  $.post('?',{jajax:"mf_gm_skip",id_game:__id_game},function(xml) {
     html=$("html",xml).text();
     if (html==1) {$(".bt").hide();}
  });
  $('input#_st_mess').focus();
}

function doPrison(t,id_prison) {
  _bt_anim(t);
  $.post('?',{jajax:"mf_gm_prison",id_game:__id_game,id_prison:id_prison},function(xml) {
     html=$("html",xml).text();
     if (html==1) {$(".bt").hide();}
  });
  $('input#_st_mess').focus();
}

function doCheck(t,id) {
  _bt_anim(t);
  $.post('?',{jajax:"mf_gm_check",id_game:__id_game,id_check:id},function(xml) {
     html=$("html",xml).text();
     if (html!='') {
       $("#id_role_"+$("id_check",xml).text()).html(html);  
       $(".bt").hide();
     }
  });
  $('input#_st_mess').focus();
}

function doDoc(t,id) {
  _bt_anim(t);
  $.post('?',{jajax:"mf_gm_doc",id_game:__id_game,id_check:id},function(xml) {$(".bt").hide();});
  $('input#_st_mess').focus();
}


function doKill(t,id) {
  _bt_anim(t);
  $.post('?',{jajax:"mf_gm_kill",id_game:__id_game,id_kill:id},function(xml) {
     html=$("html",xml).text();
  });
  $('input#_st_mess').focus();
}

function doManiac(t,id) {
  _bt_anim(t);
  $.post('?',{jajax:"mf_gm_maniac",id_game:__id_game,id_kill:id},function(xml) {
     html=$("html",xml).text();
  });
  $('input#_st_mess').focus();
}

function doFrost(t,id) {
  _bt_anim(t);
  $.post('?',{jajax:"mf_gm_frost",id_game:__id_game,id_frost:id},function(xml) {
     html=$("html",xml).text();
  });
  $('input#_st_mess').focus();
}

function doSuicide() {
  if (last_game_status<100 || __game_status<100) {
     if (confirm('Желаете сбежать из игры?')) {
        $.post('?',{jajax:"mf_gm_sucide",id_game:__id_game},function(xml) {location.reload();});
     }
  }
  $('input#_st_mess').focus();
}

function doOnStreet() {
  if (last_game_status>99 || fl_stop==1 || __game_status>99 || last_im_status!=0) {
     $.blockUI({message:'<span class="ui_warning">...выход на улицу...</span>'});
     location.href="/?";
  }
}

function doCBScroll(checked) {
   fl_scroll_chat=!checked;
}

function doScrollDown() {
   fl_scroll_chat_mem=fl_scroll_chat;
   fl_scroll_chat_now=true;
   fl_scroll_chat=false;

   last_id_chat_scroll=last_id_chat_game;
   $("input#cb_scroll").attr("checked", "checked");
}

function doScrollUp() {
   fl_scroll_chat=fl_scroll_chat_mem;
   fl_scroll_chat_now=false;
   last_id_chat_scroll=-1;
   $('#id_mess_scroll').hide();
   $('#id_mess_scroll').html('');
   $('#id_mess_scroll_hide').html('');
   if (!fl_scroll_chat) {$("input#cb_scroll").attr("checked", "checked");} else {$("input#cb_scroll").attr("checked", "");}
}


function doScrollDownSys() {
//   fl_scroll_chat_sys=false;
}

function doScrollUpSys() {
//   fl_scroll_chat_sys=true;
}


function doScrollUpOut() {
/*  if ($('#id_mess_scroll').is(':visible')) {
    doScrollUp();
  }*/
}

function mf_game_last_click() {
     $.post('?',{jajax:"mf_game_last_click",id_game:__id_game,gs:__game_status},function(xml) { });
     setTimeout('mf_game_last_click();',7000);  
}

//=======================

function runAutoExit() {
  if (fl_sec_autoexit) {
     if (__gameautoexit<1) {
        doOnStreet();
     } else {
       $('td#id_sec_autoexit').html(__gameautoexit);
       __gameautoexit--;
       to_autoexit=setTimeout('runAutoExit();',1000);
     }
  }
}

function stopAutoExit() {
   fl_sec_autoexit = false;
   $('#id_on_street').hide();
}

//====================== PLAY

var h_str;
var hi=0;
var h_pause = false;
var tid_play;
var fl_mg_playing = false;

function mgPlay() {
  if (hi>0) {
    h_pause=false;
    _mgPlay();
    $('img#id_bt_play').attr({src:'?imgivw=mg_play_grey'});         $('img#id_bt_pause').attr({src:'?imgivw=mg_pause'});         $('img#id_bt_stop').attr({src:'?imgivw=mg_stop'});  $('img#id_bt_playend').attr({src:'?imgivw=play-end'});
  } else {
    $.blockUI({message:'<img src="/images/wait_gr.gif" border="0"/>'});
    $.post('?',{jajax:"mf_get_play",id_game:__id_game},function(xml) {
      $.unblockUI();
      s=$("html",xml).text();
      hi=0;
      if (s!='') {
         $('#id_game_chat').html('');
         $('#id_game_chat_sys').html('');
         h_str=s.split('[%ar%]');
//alert(h_str);
         h_pause = false;
         $('img#id_bt_play').attr({src:'?imgivw=mg_play_grey'});         $('img#id_bt_pause').attr({src:'?imgivw=mg_pause'});         $('img#id_bt_stop').attr({src:'?imgivw=mg_stop'});  $('img#id_bt_playend').attr({src:'?imgivw=play-end'});
         _mgPlay();
      }
    });
  }
}

function mgPlayEnd() {
   location.href="/mfgame"+__id_game+"/";
}

function _mgPlay() {
   if (hi<h_str.length && !h_pause) {
       fl_mg_playing = true;

      ar=h_str[hi].split('[%s%]'); 
      $('#id_time_game_end').html(ar[2]);

      if (ar[0]=='do') {
         _draw_clients(ar[3],ar[5],ar[4],true);
      } 

      if (ar[0]=='mess') {
        if (__game_chat_pos!='bottom' || parseInt(ar[1])==0 || parseInt(ar[1])==2 || parseInt(ar[1])==9) {
          $('#id_game_chat').append(ar[3]);
          $('#id_game_chat').attr('scrollTop',$('#id_game_chat').attr('scrollHeight'));
        } 
        if (__game_chat_pos=='bottom' && parseInt(ar[1])!=0) {
          $('#id_game_chat_sys').append(ar[3]);
          $('#id_game_chat_sys').attr('scrollTop',$('#id_game_chat_sys').attr('scrollHeight'));
        }
      }
      hi++;
      tid_play=setTimeout('_mgPlay();',800);
   } else {
      mgStop();
   }
}

function mgPause() {
  clearTimeout(tid_play);
  h_pause=true;
  $('img#id_bt_play').attr({src:'?imgivw=mg_play'});         $('img#id_bt_pause').attr({src:'?imgivw=mg_pause_grey'});         $('img#id_bt_stop').attr({src:'?imgivw=mg_stop'});  $('img#id_bt_playend').attr({src:'?imgivw=play-end'});
}

function mgStop() {
  fl_mg_playing = false;
  clearTimeout(tid_play);
  h_pause=true;
  hi=0;
  $('img#id_bt_play').attr({src:'?imgivw=mg_play'});         $('img#id_bt_pause').attr({src:'?imgivw=mg_pause_grey'});         $('img#id_bt_stop').attr({src:'?imgivw=mg_stop_grey'});  $('img#id_bt_playend').attr({src:'?imgivw=play-end-grey'});

}

function doHistoryStep(day, night) {
//  $.blockUI({message:'<img src="/images/wait_gr.gif" border="0"/>'});
  memxy=mousexy;
  $('td#hs_login').html('История сообщений: ');
  $.post('?',{jajax:"mf_htmlchat",_i_id_game:__id_game,_i_day:day,_i_night:night,_s_tp_chat:'_chat_history_dn'},function(xml) {
//      $.unblockUI();
      w=Math.round($(window).width()/3);
      $('#id_mess_history_html').html($("html",xml).text());
      if (__game_status<100 && __game_chat_pos=='bottom') {l=$(window).width()-w-150;} else {l=100;}  
      l1=$('#id_place_chat').offset().left+8;
      t1=$('#id_place_chat').offset().top-4;
      h1=$('#id_place_chat').height()-150;
      w1=$('#id_place_chat').width()-120;
//      $("#id_mess_history_html").css({height:$(window).height()-200,width:w});
      $("#id_mess_history_html").css({height:h1,width:w1});
      $("#id_mess_history").animate({
//          left: l, top:50, opacity: 'show', width:w+40, 
          left: l1, top:t1, opacity: 'show', width:w1+40, height:h1+40
       }, 200);
       $('input#_st_mess').focus();
   });
}

/*
function drawDayNightHistory(gs, dn) {
  day=dn; night=dn; if (gs==3) {day--; night--;} if (gs==4) {night--;}
  s='';
  for (i=0; i<=dn; i++) {
    s+='<div style="float:left;">';
    if (i>0) {
       if (i<=day) {s+='<div class="hist-dn hist-day" onclick="doHistoryStep('+i+',0);">'+i+'</div>';}
       if (i<=night) {s+='<div class="hist-dn hist-night" onclick="doHistoryStep(0,'+i+');">'+i+'</div>';}
    } else {
       if (dn>0) {s+='<div class="hist-dn hist-handshake" onclick="doHistoryStep(0,0);">&nbsp;</div>';}
    }

    s+='</div>';
  }

  $('#id_dn_history').html('<div style="height:60px;">'+s+'</div>');
  jQuery("#id_dn_history").jScrollHorizontalPane();
}*/


function drawDayNightHistory(gs, dn) {
  day=dn; night=dn; if (gs==3) {day--; night--;} if (gs==4) {night--;}
  s='';
  for (i=0; i<=dn; i++) {
    s+='<div style="float:left;">';
    if (i>0) {
       if (i<=day) {s+='<div class="hist-dn hist-day" onclick="doHistoryStep('+i+',0);">'+i+'</div>';}
       if (i<=night) {s+='<div class="hist-dn hist-night" onclick="doHistoryStep(0,'+i+');">'+i+'</div>';}
    } else {
       if (dn>0) {s+='<div class="hist-dn hist-handshake" onclick="doHistoryStep(0,0);">&nbsp;</div>';}
    }

    s+='</div>';
  }

  $('#id_dn_history').html(s);
}

function menuInit() {
   jkoutlinemenu.definemenu("id_gm_menu", "mymenu", "mouseover");
}

//=========================

function __start_game() {

    if (__game_status>99) { 
       $('#id_place_play').html($('#id_tmp_play').html());
       $('#id_tmp_play').children().remove();
    }

  if (__game_status<100) {
     game_redraw();
     tm_total = new totimer('tm_total','#id_time_game',__glsec,-1, true);
     tm_total.start();
     tm_step = new totimer('tm_step','#id_timer_step',__step_sec_remain,0, false, function() {nextStep();});
     tm_step.start();
     $('img#bt_on_street').hide();
  } else {
     $('#id_tmp_play').show(); 
     $('img#bt_suicide').hide();
     $('img#bt_on_street').show();
     if (__from_begin==0) {
        html_game_redraw();
     } else {
        mgPlay();
     }
  }
 
/*  w_table=0;
  $('.gm-cl').each(
     function() {
        w=$('#'+this.id).width(); 
        w_table=Math.max(w_table,w);
     }  
  )
  w_table+=15;
  $('.gm-cl').width(w_table);*/

  $('input#_st_mess').focus();

  if (__game_chat_pos=='bottom') {
      w=$('#id_place_chat').width();
  } else {
      w=$('#id_place_chat_sys').width();
  }
//  $('#id_dn_history').css({width:w-50});

}

function onMouseOverGamer(id) {
  if ($('#id_bt_do_'+id).html()=='' || __id_client==id) {
     $('#id_role_'+id).hide();
     $('#id_gamer_'+id+' .status-text').hide();
     $('#id_td_pr_'+id).hide();
  } else {
     $('#id_role_'+id).addClass('opacity-gamer-over');
     $('#id_gamer_'+id+' .status-text').addClass('opacity-gamer-over');
     $('#id_td_pr_'+id).addClass('opacity-gamer-over');
  }
  $('#id_to_'+id).css('font-size','24px');
  $('#id_pr_'+id).css('font-size','24px');
}

function onMouseOutGamer(id) {
  $('#id_role_'+id).removeClass('opacity-gamer-over').show();
  $('#id_gamer_'+id+' .status-text').removeClass('opacity-gamer-over').show();
  $('#id_td_pr_'+id).removeClass('opacity-gamer-over').show();
  $('#id_to_'+id).css('font-size','12px');
  $('#id_pr_'+id).css('font-size','12px');
}


function htmlGamerTable(twidth,id,login,gender,fl_bolvan,ip_cross,opinion,login_true,fl_alias) {
  html='';
  html+='<table id="id_gamer_'+id+'" height="'+h_table+'" width="'+twidth+'" cellpadding="4" cellspacing="0" class="gm-cl" fl_bolvan="'+fl_bolvan+'" onmouseover="onMouseOverGamer('+id+');" onmouseout="onMouseOutGamer('+id+');">';
  html+='<tr valign="top"><td width="20" style="background-image: url(?imgivw=bg_tl);" class="bg-tl">';
  html+='<div id="id_status_img_'+id+'" onclick="viewMessHistory('+id+',\''+login+'\');" class="cp inline">';
  if (fl_alias==1) {gender='man';} 
  html+='<img src="?imgivw=gm_'+gender+'" align="left"/>';
  html+='</div>';
  html+='</td><td colspan="2"  style="background-image: url(?imgivw=bg_tr);" class="bg-tr">';
//                    <xsl:if test="(//im/@fl_send_mess_private>0) and (@cl_status=0)">
  html+='<div class="id_bt_gm cp inline" id="id_login_'+id+'" login="'+login+'" idcl="'+id+'">';
//                    </xsl:if>
  if (__game_status>99) {
     html+='<a href="/?cl_stat='+id+'" onclick="doCLInfoFloat('+id+'); return false;"><img src="?imgivw=info" border="0"></a>';
  }
  html+=login+'</div>';
//                    <xsl:if test="(//im/@fl_send_mess_private>0) and (@cl_status=0)">
//                        <xsl:value-of select="concat('','&lt;/div&gt;')" disable-output-escaping="yes"/>
  if (__game_status<99) {  
     html+='<div>';
     html+='<div id="id_to_'+id+'" class="mess-to" onclick="_doTOClient(\''+login+'\');">[to]</div>';
//     html+='<div id="id_pr_'+id+'" class="mess-pr" onclick="_doPRClient(\''+login+'\');">[pr]</div>';
     html+='<div id="id_pr_'+id+'" class="mess-pr" onclick="viewSendPrivate(\''+login+'\');">[pr]</div>';
     html+='</div>';
  }
  html+='<div class="sm-win" id="id_sm_win_'+id+'"></div><div class="sm-los" id="id_sm_los_'+id+'"></div><div class="sm-step0" id="id_sm_step0_'+id+'"></div>';
//                    </xsl:if>
  if (__game_status>99) {html+='<div class="login_true">'+login_true+'</div>';}
  if (ip_cross!='') {html+='<div class="ip_cross">'+ip_cross+'</div>';}
  html+='<div id="cl_delay_'+id+'" class="cl_delay hide"></div>';
  html+='</td></tr>';
  html+='<tr valign="top"><td colspan="3">';
  html+='<div class="role" id="id_role_'+id+'"></div>';
  html+='<div class="status-text" id="id_status_text_'+id+'"></div>';
  html+='</td></tr>';
  html+='<tr valign="top"><td colspan="3">';
  html+='<div id="id_td_pr_'+id+'">';
  html+='<div class="count-prison" id="id_cou_prison_'+id+'"></div>';
  html+='<div class="prison-login" id="id_prison_login_'+id+'"></div>';
  html+='</div>';
  html+='</td></tr>';
  html+='<tr valign="bottom">';
  html+='<td align="left" style="background-image: url(?imgivw=bg_bl);" class="bg-bl"></td>';
  html+='<td align="left" class="bg-bl">';
  if (__game_status<99) {html+='<div id="id_op_'+id+'" class="bt-opinion" onclick="showOpinion('+id+');">{'+opinion+'}</div>';}
  html+='</td>';
  html+='<td align="right" class="bt-do bg-br" width="20" style="background-image: url(?imgivw=bg_br);">';
  html+='<div id="id_bt_do_'+id+'"></div>';
  html+='<div id="id_bt_do_2_'+id+'"></div>';
  html+='</td>';
  html+='</tr>';
  html+='</table>';
  return html;
}

function showTableChatOptions() {
   memxy=mousexy;
   w = $('#id_float_chat_options').width()+20;
   $('#id_float_chat_options').animate({
          left: memxy.x-w, top:memxy.y, opacity: 'show'
   }, 500);
}

function hideTableChatOptions() {
  $('#id_float_chat_options').hide();
}

function gameDrawField() {
  $.blockUI({message:'<img src="/images/wait_gr.gif" border="0"/>'});
  $.post('?',{jajax:"mf_game_draw",id_game:__id_game},function(xml) {

      gs=parseInt($("game_status",xml).text());
      fl_alias=parseInt($("fl_alias",xml).text());
      html=$("html",xml).text();
      ar1=html.split('+++');

      wt=w_table+10;
      w=$(window).width();
      h_minus=0;
      ht='<table width="99%" border="0"  cellpadding="2" cellspacing="2" id="id_tbl_field">';
      switch (__game_chat_pos) {
         case 'right':
            w1=w*0.66;
            cols=Math.floor(w1/wt);
            w1=cols*wt;
            
            ht+='<tr valign="top"><td width="'+w1+'" id="id_td_col_1" rowspan="3"></td><td><div id="id_place_chat"></div></td></tr>';
            if ($.browser.msie) {
                if (__game_status<99) {ht+='<tr><td height="20"></td></tr>';}
            }  
            if (__game_status<99) {ht+='<tr><td style="padding:45px 0 0 15px;"><div id="id_dn_history"></div></td></tr>'; h_minus+=30;}
            if (__game_status>99) {ht+='<tr><td><div id="id_place_play"></div></td></tr>'; h_minus+=30;}

         break;
         case 'center':
            cols=Math.floor(w/wt);
            w1=cols*wt;
            wperc=Math.floor(100/cols);
            w1=Math.floor((w-cols*7)/cols);
            colspan=cols-2;
            h=$(window).height()-$('table#id_tbl_field_title').height()-20;
            rows=Math.floor(h/(h_table+10));
            rowspan=rows-2;

            if (cols+rowspan*2>=ar1.length) rowspan++;
            if (rowspan<2) rowspan=2;
//_debug(cols+' '+wperc+'% colspan='+colspan+' rowspan='+rowspan+' rows='+rows);

            ii=0;

            ht+='<tr>';

            var td = new Array();
            for (i=0; i<cols; i++) {td[td.length]='';}
 
            for (i=0; i<cols; i++) {
               if (ii<ar1.length) {ar=ar1[ii].split('|');  html=htmlGamerTable('100%',parseInt(ar[0]),ar[1],ar[2],parseInt(ar[3]),ar[4],ar[5],ar[6],fl_alias); ii++;} else {html='&nbsp;';}
               s1='<td width="'+w1+'" nowrap="nowrap">'+html+'</td>';
               if (gs==5) {
                  if (i<=1) {td[i+1]=s1;} else {if (i==2) {td[0]=s1;} else {td[i]=s1;}}
               } else {
                 td[i]=s1;
               }
            }

            ht+=td.join('');
            ht+='</tr>';

            for (j=0; j<rowspan; j++) {
                 ht+='<tr valign="top">';
                 if (ii<ar1.length) {ar=ar1[ii].split('|');  html=htmlGamerTable('100%',parseInt(ar[0]),ar[1],ar[2],parseInt(ar[3]),ar[4],ar[5],ar[6],fl_alias); ii++;} else {html='&nbsp;';}
                 ht+='<td height="'+h_table+'">'+html+'</td>';
                 if (j==0) { 
                    ht+='<td colspan="'+colspan+'"><div id="id_place_chat" style="margin:0px 0 0 5px;"></div></td>';
                 }
                 if (ii<ar1.length) {ar=ar1[ii].split('|');  html=htmlGamerTable('100%',parseInt(ar[0]),ar[1],ar[2],parseInt(ar[3]),ar[4],ar[5],ar[6],fl_alias); ii++;} else {html='&nbsp;';}
                 ht+='<td>'+html+'</td>';
                 ht+='</tr>';
            }

            if (ii<ar1.length) {
              for (j=0; j<10; j++) {
                 ht+='<tr valign="top">';
                 for (i=0; i<cols; i++) {
                    if (ii<ar1.length) {ar=ar1[ii].split('|');  html=htmlGamerTable('100%',parseInt(ar[0]),ar[1],ar[2],parseInt(ar[3]),ar[4],ar[5],ar[6],fl_alias); ii++;} else {html='&nbsp;';}
                    ht+='<td>'+html+'</td>';
                 }
                 ht+='</tr>';
                 if (ii>=ar1.length) break;
              }
            }

            ht+='<tr><td>&nbsp;</td><td colspan="'+colspan+'">';
            if (__game_status<99) {ht+='<div id="id_dn_history"></div>';}
            if (__game_status>99) {ht+='<br/><div id="id_place_play"></div>'; h_minus+=30;}
            ht+='</td><td>&nbsp;</td></tr>';

          if (__game_status<99) {h_minus+=30;}
          $('#id_place_chat').css({height:h_table*rowspan-25-h_minus});
          $('#id_game_chat').css({height:h_table*rowspan-25-h_minus});

         break;
         case 'bottom':
            cols=Math.floor(w/wt);
            w1=cols*wt;
//_debug(' wt='+wt+' w='+w+' w1='+w1);
            ht+='<tr valign="top"><td id="id_td_col_1" colspan="2"></td></tr>';
//            if ($.browser.msie) {
               ht+='<tr valign="top"><td width="50%"><div id="id_place_chat"></div></td>';
//            } else {
//               ht+='<tr valign="top"><td width="'+Math.round(w/2)+'"><div id="id_place_chat"></div></td>';
//            } 
            ht+='<td><div id="id_place_chat_sys">';
//            ht+='<div id="id_game_chat_sys" onmousedown="doScrollDownSys();" onmouseup="doScrollUpSys();" ></div>';
            ht+='</div></td></tr>';
            ht+='<tr><td></td><td>';
            if ($.browser.msie) {
                if (__game_status<99) {ht+='<br/>';}
            }  
            if (__game_status<99) {ht+='<br/><div id="id_dn_history"></div>'; h_minus+=30;}
            ht+='</td></tr>';
            ht+='<tr><td></td><td>';
            if (__game_status>99) {ht+='<div id="id_place_play"></div>'; h_minus+=30;}
            ht+='</td></tr>';

         break;
      }
      ht+='</table>';

      $('#id_body_game').html(ht);

//_debug($(window).height()+'-'+$('table#id_tbl_field_title').height()+'+'+h);
      $('#id_place_chat').html(html_chat);

      if (__game_chat_pos!='center') {
        for (i=0; i<ar1.length; i++) {
            ar=ar1[i].split('|');
//alert(ar);
            html=htmlGamerTable(w_table,parseInt(ar[0]),ar[1],ar[2],parseInt(ar[3]),ar[4],ar[5],ar[6],fl_alias); 
            $('td#id_td_col_1').append(html);
        }
      }

      switch (__game_chat_pos) {
         case 'right':
            h=$(window).height()-$('table#id_tbl_field_title').height()-110-h_minus;
         break;
         case 'bottom':
            h=$(window).height()-$('table#id_tbl_field_title').height()-$('table#id_tbl_field').height()-h_minus;
         break;
         case 'center':
         break;
      }

      if (__game_chat_pos!='center') {
          if (h<200) h=200;
//          h=h-$('table#id_tbl_field').height()-100;
          $('#id_place_chat').css({height:h+40});
          $('#id_game_chat').css({height:h});
      }

      if (__game_chat_pos=='bottom') {
          $('#id_place_chat_sys').html($('#id_tmp_chat_sys').html());
          $('#id_tmp_chat_sys').children().remove();

          $('#id_place_chat_sys').css({height:h});
          $('#id_game_chat_sys').css({height:h});

/*          $('#id_place_chat').css({height:h});
          $('#id_game_chat').css({height:h});*/

/*alert($('#id_game_chat_sys').height()+' '+$('#id_place_chat_sys').height());
$('#id_game_chat').css({height:h});
$('#id_place_chat').css({height:$('#id_place_chat_sys').height()});*/

      }


      __start_game();

      $('input#_st_mess').css({width:$('#id_game_chat').width()-20});

//      if (__ip=='127.0.0.1') {$('.ip_cross').addClass('hide');}

      $.unblockUI();
 });
}

$(document).ready(function() {

   if (__id_game>0) {

      $('#id_tmp_chat_inner').hide(); $('#id_tmp_gamers').hide();

      gameDrawField(true);

//      mf_game_last_click();
   }

});

$(window).resize(function() { if (__id_game>0 && !fl_mg_playing) {
  if (!$.browser.msie) {
      location.href="/mfgame"+__id_game+"/";
  }
//      gameDrawField();
}});

var to_streetchat;

var last_id_chat_street = -1;
var fl_st_pr_en = true;
var fl_scroll_chat_street=true;
var flLayout = 'v';
var ar_chat = new Array();
var _ss_click = false;
var fl_blink_notify_street = false;
var street_mem_title='';
var street_prev_title='';

var fl_schat_common = 1;
var fl_schat_pr = 1;
var fl_schat_to = 1;
var fl_schat_to_common = 1;

function sm2inp(img) {
  s=img.src; ar=s.split('/'); s=ar[ar.length-1]; ar=s.split('.'); sm=ar[0];
  v=$('input#_st_mess').val();
  $('input#_st_mess').val(v+' :'+sm+': ');
  closeSmileStreet();
  $('input#_st_mess').focus();
}

function showSmiles() {
   var memxy=mousexy;
   $("#id_smiles_street").animate({
          left: memxy.x, top:$(window).height()-260, opacity: 'show'
   }, 500);
   fl_open_smiles=true;
   if (!currSmileIMG) setSmileSelNext(1);
}

function doShowCreateGame() {
  if (__mg_status==2) {alert('Вы не можете создавать партию под арестом');  return;}
  var memxy=mousexy;
  $.blockUI({message:'<img src="/images/wait_gr.gif" border="0"/>'});
  $.post('?',{jajax:"mf_show_create_game"},function(xml) {
      $.unblockUI();
      $("#id_create_game").html($("html",xml).text());
//      if (flLayout=='v') {left=memxy.x-275;} else {left=memxy.x+20;}
      if (flLayout=='v') {left=$(window).width()-700;} else {left=100;}
      $("#id_create_game").animate({left: left, top:30, width:550, opacity: 'show'}, 1000);
      setMemCG('cb_maniac',true);      setMemCG('cb_open_role',true);      setMemCG('cb_alias',true);      setMemCG('cb_duel',true);      setMemCG('cb_boss',true);      setMemCG('cb_vsb',true);      setMemCG('cb_bots',true);  setMemCG('cb_doc',true);  setMemCG('cb_buy',true);
      setMemCG('cou_gamer_min',false);      setMemCG('cou_gamer_max',false);      setMemCG('wait_min',false);      setMemCG('length_meet',false);      setMemCG('length_day',false);      setMemCG('length_night',false);  setMemCG('stake_one',false);
  });
}

function doShowRoleBuy(id_game) {
  if (__mg_status==2) {return;}
  var memxy=mousexy;
  $.blockUI({message:'<img src="/images/wait_gr.gif" border="0"/>'});
  $.post('?',{jajax:"mf_show_role_buy",id_game:id_game},function(xml) {
      $.unblockUI();
      fl_buy=parseInt($("fl_buy",xml).text());
      if (fl_buy==1) {
          $("#id_role_buy").html($("html",xml).text());
          if (flLayout=='v') {left=$(window).width()-700;} else {left=100;}
          $("#id_role_buy").animate({left: left, top:30, width:550, opacity: 'show'}, 1000);
      } else {
          doJoinToGame(parseInt($("id_game",xml).text()),true);
      }
  });
}

function hideCreateGame() {
   $("#id_create_game").animate({left: 0, top:0, width:0, opacity: 'hide'}, 500, '', function() {$("#id_create_game").html('');});
   $('input#_st_mess').focus();
}

function hideRoleBuy() {
   $("#id_role_buy").animate({left: 0, top:0, width:0, opacity: 'hide'}, 500, '', function() {$("#id_role_buy").html('');});
   $('input#_st_mess').focus();
}

function doCreateGame() {
  $.blockUI({message:'<img src="/images/wait_gr.gif" border="0"/>'});
  if ($('input[name=cb_boss]').attr('checked')) {fl_boss=1;} else {fl_boss=0;}
  if ($('input[name=cb_vsb]').attr('checked')) {fl_vsb=1;} else {fl_vsb=0;}
  if ($('input[name=cb_maniac]').attr('checked')) {fl_maniac=1;} else {fl_maniac=0;}
  if ($('input[name=cb_alias]').attr('checked')) {fl_alias=1;} else {fl_alias=0;}
  if ($('input[name=cb_bots]').attr('checked')) {fl_bots=1;} else {fl_bots=0;}
  if ($('input[name=cb_doc]').attr('checked')) {fl_doc=1;} else {fl_doc=0;}
  if ($('input[name=cb_duel]').attr('checked')) {fl_duel=1;} else {fl_duel=0;}
  if ($('input[name=cb_buy]').attr('checked')) {fl_buy=1;} else {fl_buy=0;}
  if ($('input[name=cb_open_role]').attr('checked')) {fl_open_role=1;} else {fl_open_role=0;}
  $.post('?',{jajax:"mf_create_game",wait_min:$('input#wait_min').val(),cou_gamer_min:$('input#cou_gamer_min').val(),fl_vote:$('input[name=rb_vote]:checked').val(),length_meet:$('input#length_meet').val(),
                 fl_boss:fl_boss,_i_fl_maniac:fl_maniac, fl_vsb:fl_vsb,cou_gamer_max:$('input#cou_gamer_max').val(),fl_alias:fl_alias,fl_duel:fl_duel,fl_bots:fl_bots,fl_doc:fl_doc,fl_buy:fl_buy,
                 fl_open_role:fl_open_role,_st_login_access:$('input#login_access').val(),id_tour:$('select#id_tour').val(), sm_stake:$('input#sm_stake').val(),
                 length_day:$('input#length_day').val(),length_night:$('input#length_night').val()},function(xml) {
     $.unblockUI();
     html=$("html",xml).text();
     if (html=='ok') {
        fl_buy=parseInt($("fl_buy",xml).text());
        hideCreateGame();
        if (fl_buy==1) {
           doShowRoleBuy(parseInt($("id_game",xml).text()));
        }
        fl_check_game_in=true;
//        html_street_games();
     } else {
        alert(html);  
     }
  });
}

function doRoleBuy() {
  role=$('input[name=rb_buy]:checked').val();
  id_game_buy=$('input#game_buy').val();
  my_cost=$('input#inp_my_cost').val();  my_cost=my_cost.replace(/,/gi,'.'); my_cost=parseFloat(my_cost); if (isNaN(my_cost)) {my_cost=0;}
  my_money=$('input#inp_my_money').val();  my_money=my_money.replace(/,/gi,'.'); my_money=parseFloat(my_money); 
  if (role!='-1') {
    sel_cost=$('td#cost_'+role).html(); sel_cost=sel_cost.replace(/,/gi,'.'); sel_cost=parseFloat(sel_cost);
  } else {
    sel_cost=0;
  }
  if (sel_cost>0) {
     if (my_cost>0 && my_cost>sel_cost) {sm=my_cost;} else {sm=sel_cost;}
     if (my_money<sm) {
         alert('У вас недостаточно средств на счету для покупки');
         return;
     }
  } else {
//     hideRoleBuy();
  } 
  $.blockUI({message:'<img src="/images/wait_gr.gif" border="0"/>'});
  $.post('?',{jajax:"mf_role_buy",role:role,id_game_buy:id_game_buy,my_cost:my_cost},function(xml) {
     $.unblockUI();
     html=$("html",xml).text();
     if (html=='ok') {
        hideRoleBuy();
//        html_street_games();
     } else {
        alert(html);  
     }
  });
}


function doJoinToGame(id_game,fl_force) {
  if (__mg_status==2) {alert('Вы не можете присоединяться к партии под арестом');  return;}
  if (__id_tour==0 && !fl_force) {
     doShowRoleBuy(id_game);
  } else {
    $.blockUI({message:'<img src="/images/wait_gr.gif" border="0"/>'});
    $.post('?',{jajax:"mf_join_cl2game",id_game:id_game},function(xml) {
       $.unblockUI();
       html=$("html",xml).text();
       if (html=='ok') {
          fl_check_game_in=true;
          $('input#_st_mess').focus();
       } else {
          alert(html);  
       }
    });
  }
}

function doJoinToGameBot(id_game) {
  $.blockUI({message:'<img src="/images/wait_gr.gif" border="0"/>'});
  $.post('?',{jajax:"mf_join_cl2game_bot",_i_id_game:id_game},function(xml) {
     $.unblockUI();
     $('input#_st_mess').focus();
//     html_street_games();
  });
}

function notifyStreetMessHide() {
  if (fl_blink_notify_street) {fl_blink_notify_street=false;  document.title=street_mem_title;}
}

function doStreetMess(e,v) {
  var keynum;
  var keychar;

  if(window.event) {keynum = e.keyCode;} else if(e.which) {keynum = e.which;}
  keychar = String.fromCharCode(keynum);
  notifyStreetMessHide();
//_debug(keynum);
  v=v.replace(/^s*/, "").replace(/s*$/, "");
  if (keynum==13 && fl_open_smiles) {
    if (currSmileIMG) sm2inp(currSmileIMG);
  } else {
    if (keynum==13 && v!='') {
	  $('input#_st_mess').val('');
          if (v=='') return false;
          v=escape(v);

//                  clearTimeout(to_streetchat);
//                  street_chat(v);

          $.post('?',{jajax:"mf_sendchatmess",_s_mess:v},function(xml) {
                  clearTimeout(to_streetchat);
                  street_chat();
//         	  html_street_chat();
          });

    }
  }
  if (keynum==27) {
    if (fl_open_smiles) {
       closeSmileStreet();
    } else {
        $('input#_st_mess').val('');
    }

     $('input#_st_mess').focus();
  }
/*  if (keynum==83 && !_ss_click && !fl_open_smiles) {
     _ss_click=true;
     setTimeout('_ss_click=false;',400);
  } else {
     if (keynum==83 && _ss_click && !fl_open_smiles) {
        v=$('input#_st_mess').val();
        v=v.replace(/(sss*|ыыы*)/,'');
        $('input#_st_mess').val(v);
        showSmiles();
       _ss_click=false;
     }
  }*/
  if (keynum==40 && fl_open_smiles) {setSmileSelNext(5);}
  if (keynum==38 && fl_open_smiles) {setSmileSelNext(-5);}
  if (keynum==37 && fl_open_smiles) {setSmileSelNext(-1);}
  if (keynum==39 && fl_open_smiles) {setSmileSelNext(1);}
}

/*
function street_clients() {
  $.post('?',{jajax:"_street_clients",level:__level},function(xml) {
      $('#id_street_clients').html($("html",xml).text());
  });
  setTimeout('street_clients();',__to_st_cls);
}*/

function _doMessClient(t) {
   v=$('input#_st_mess').val();
   $('input#_st_mess').val('to['+t.innerHTML+'] '+v);
   $('input#_st_mess').focus();
}

function _doMessClientPR(t) {
   v=$('input#_st_mess').val();
   $('input#_st_mess').val('pr['+t.innerHTML+'] '+v);
   $('input#_st_mess').focus();
}

function _doPRLogin(login) {
   v=$('input#_st_mess').val();
   $('input#_st_mess').val('pr['+login+'] '+v);
   $('input#_st_mess').focus();
}

function _doTOLogin(login) {
   v=$('input#_st_mess').val();
   $('input#_st_mess').val('to['+login+'] '+v);
   $('input#_st_mess').focus();
}

function doChatClean() {
   ar_chat = new Array();
   $('#id_street_chat').html('');
   $('input#_st_mess').focus();
}

function html_street_chat(mess) {    if (fl_scroll_chat_street) {      if (fl_st_pr_en) {
if (!mess) mess='';
           fl_st_pr_en=false;
           $.ajax({
type: "POST",
url: "/?",
data:({jajax:"mf_htmlchat",_s_id_div:'id_street_chat',level:__level,_s_tp_chat:'_chat_street',id_last:last_id_chat_street,level:__level,fl_street_games:1,fl_street_clients:1,mess:mess}),
dataType: "xml",
timeout: 30000,
error: function(html){
                                           ping_error_count++; 
                                           if (ping_error_count>3) {
                                               $('body,table').css('cursor', 'wait'); 
                                               $('#id_ping_alert').html('Кажется, вот уже '+(__to_st_chat/1000*ping_error_count)+' секунд как пропала связь с сервером... <br>Обновить страницу? Перещёлкнуть модем? Проверить канал?'); 
                                               $('#id_ping_alert').show(); 
                                           }  
                                           fl_st_pr_en=true;
                                       },
success: function(xml) {
                                           if (ping_error_count>0) {
                                               $('body,table').css('cursor', 'default'); 
                                               $('#id_ping_alert').hide(); 
                                           }  
                                           ping_error_count = 0;

               last_id_chat_street=$("id_last",xml).text();
               
               fl_mess_to_me=parseInt($("fl_mess_to_me",xml).text());
               fl_mess_to_me_pr=parseInt($("fl_mess_to_me_pr",xml).text());
               if (fl_mess_to_me==1) {
                  fl_blink_notify_street=true;
                  titleBlinkNotifyChatStreet();
                  if (fl_mess_to_me_pr==1) playNotify();
               }

               $('#id_on_street_detail').html('на улице - '+$("cou_on_street",xml).text()+', в игре - '+$("cou_in_game",xml).text());

               html=$("html",xml).text();
               if (html!='') { 
                  ar_chat[ar_chat.length]=$("html",xml).text();
//_debug(ar_chat.length);
                  if (ar_chat.length>50) {
                      ar_chat=ar_chat.slice(ar_chat.length-50);
                  }

                 $('#id_street_chat').html(ar_chat.join(''));
               }

//               hprev=$('#id_street_chat').html();
//               $('#id_street_chat').html(hprev+$("html",xml).text());
               $('#id_street_chat').attr('scrollTop',$('#id_street_chat').attr('scrollHeight'));
//               $(".chat-login").click( function() { _doMessClient(this);} );

               to_game=$("to_game",xml).text();
               if (to_game>0) {
                    location.href="/?mf_game="+to_game;
               } else {
                    html=$("html_games",xml).text(); 
                    $('#id_street_games').html(html);
                    $("div[wait_sec]").each( function() {ws=$('#'+this.id).attr('wait_sec');  $('#'+this.id).jtimer(ws,{fl_h:false}, function() {});});
                    $('#id_street_games_active').html($("html_active",xml).text());
               }

               $('#id_street_clients').html($("html_street_clients",xml).text());

               ar_s = $("s_skins",xml).text(); ar_s = ar_s.split(',');
               for (i=0; i<ar_s.length; i++) {
                  $('#id_tab_skin_'+ar_s[i]).attr('title','игроков на улице: '+$("clcous_"+ar_s[i],xml).text()); 
                  cou=parseInt($("clcous_"+ar_s[i],xml).text()); if (cou>0) {s=' ('+cou+')';} else {s='';}
                  $('#id_skin_count_'+ar_s[i]).html(s); 
               }
               ar_sl = $("s_skinlvl",xml).text(); ar_sl = ar_sl.split(',');
               for (i=0; i<ar_sl.length; i++) {
                  $('a#id_a_lvl_'+ar_sl[i]).attr('title','игроков на улице: '+$("clcousl_"+ar_sl[i],xml).text()); 
               }

doCBSChat(0,(fl_schat_common==1));
doCBSChat(1,(fl_schat_to==1));
doCBSChat(2,(fl_schat_pr==1));
doCBSChat(3,(fl_schat_to_common==1));

              html=$("mail_notify_html",xml).text();
              if (html!='') {checkMailINExtDraw(html, $("mail_notify_id_from",xml).text(), $("mail_notify_id_mess",xml).text(), $("mail_notify_cou_unread",xml).text());}

               fl_st_pr_en=true;

             fl_reload = $("fl_reload",xml).text();
             if (fl_reload=='1') {
                  location.reload();
             }


}

           });
}}}

function street_chat(mess) {
  if (!mess) mess='';
  html_street_chat(mess);
  to_streetchat = setTimeout('street_chat();',__to_st_chat);
}

function doDeleteGame(id_game) {
  if (confirm('Удалить игру?')) {
  $.blockUI({message:'<img src="/images/wait_gr.gif" border="0"/>'});
  $.post('?',{jajax:"delete_game",_i_id_game:id_game},function(xml) {
      $.unblockUI();
//     html_street_games();
  });
  }
}

function doClientDeleteFromGame(id_game, idcl) {
  $.blockUI({message:'<img src="/images/wait_gr.gif" border="0"/>'});
  $.post('?',{jajax:"delete_client_from_game",id_game:id_game,idcl:idcl},function(xml) {
      $.unblockUI();
//     html_street_games();
  });
}

function setLayout(fl) {
  if (fl=='') {w=$(window).width(); if (w<__screen_width_chat) {fl='h';} else {fl='v';}}

  if (fl!=flLayout) {

    if (fl=='h') {
       $('td#id_h_td_chat').html($('td#id_v_td_chat').html());
       $('td#id_v_td_chat').children().remove();
 
       $('td#id_h_td_games').html($('td#id_v_td_games').html());
       $('td#id_v_td_games').children().remove();

       $('td#id_h_td_games_active').html($('td#id_v_td_games_active').html());
       $('td#id_v_td_games_active').children().remove();

       $('table#id_tbl_v').hide();
    } else {
       $('td#id_v_td_chat').html($('td#id_h_td_chat').html());
       $('td#id_h_td_chat').children().remove();

       $('td#id_v_td_games').html($('td#id_h_td_games').html());
       $('td#id_h_td_games').children().remove();

       $('td#id_v_td_games_active').html($('td#id_h_td_games_active').html());
       $('td#id_h_td_games_active').children().remove();

       $('table#id_tbl_h').hide();
    }
    flLayout=fl;

  }

  if ($.browser.msie) {
     hm=190;
  } else {
    if ($.browser.opera) {hm=140;} else {hm=140;}
  }

  if (fl=='v') {
        if ($.browser.msie) {
           $('table#id_tbl_v').width($(window).width()-200-20);
        }
       $('#id_v_td_chat').width(Math.round($('table#id_tbl_v').width()/2));
       $('#id_v_td_games').width(Math.round($('table#id_tbl_v').width()/2));
       $('#id_v_td_games_active').width(Math.round($('table#id_tbl_v').width()/2));

       $('#id_street_games').css({height:Math.round(($(window).height()-hm)/2-20)});
       $('#id_street_games_active').css({height:Math.round(($(window).height()-hm)/2-35)});
       $('#id_street_clients').css({height:$(window).height()-hm});
       if (__id_client>0) {
          $('#id_street_chat').css({height:$(window).height()-hm-30});
       } else {
          $('#id_street_chat').css({height:$(window).height()-hm-2});
       }
  } else {
       $('#id_h_td_games').width(Math.round($('table#id_tbl_h').width()/2));
       $('#id_h_td_games_active').width(Math.round($('table#id_tbl_h').width()/2));
       $('#id_street_games').css({height:Math.round(($(window).height()-hm)/2-20)});
       $('#id_street_games_active').css({height:Math.round(($(window).height()-hm)/2-20)});
       $('#id_street_clients').css({height:$(window).height()-hm});
       if (__id_client>0) {
          $('#id_street_chat').css({height:Math.round(($(window).height()-hm)/2-55)});  
       } else {
          $('#id_street_chat').css({height:Math.round(($(window).height()-hm)/2-2)});  
       } 
  }

  $(window).trigger('reflow');

  $('table#id_tbl_'+flLayout).show();

  $('#_st_mess').css({width:$('#id_street_chat').width() - 20});

}

function doSwitchView() {
}

function doMemCG(nm,v,fl_cb) {
  if (fl_cb) {if (v) {v=1;} else {v=0;}} 
  $.cookie(nm, v);
}

function setMemCG(nm,fl_cb) {
  v=$.cookie(nm);
  if (v==null) return;
  if (fl_cb) {
    if (v==1) {v='checked';} else {v='';} 
    $('input#'+nm).attr('checked',v);
  } else { 
    $('input#'+nm).val(v);
  }
}

function titleBlinkNotifyChatStreet() {
  if (fl_blink_notify_street) {
     s1='/// ВАМ СООБЩЕНИЕ /// ';     s2='--- ВАМ СООБЩЕНИЕ --- ';     s3=' ВАМ СООБЩЕНИЕ  ';
     if (street_prev_title==s1+street_mem_title) {
        street_prev_title=s2+street_mem_title; 
     } else {
        if (street_prev_title==s2+street_mem_title) {
           street_prev_title=s3+street_mem_title; 
        } else {
           street_prev_title=s1+street_mem_title;
        } 
     }
     document.title=street_prev_title;
     setTimeout('titleBlinkNotifyChatStreet();',800);  
  }
}

/*function playNotify() {
      $('#id_mail_notify_wma').html('<a id="id_media_mn" class="media" href="/images/mail_notify.wma"></a>');
      $('a#id_media_mn').media({autoplay: true, width:0, height:0});
 }*/

function showTableSChatOptions() {
   memxy=mousexy;
   $('#id_float_schat_options').animate({
          left: memxy.x, top:memxy.y-30, opacity: 'show'
   }, 500);
}

function hideTableSChatOptions() {
  $('#id_float_schat_options').hide();
}

function doCBSChat(tp,checked) {
     switch (tp) {
       case 0: if (checked) {$('tr[fl_common=1]').show(); fl_schat_common = 1;} else {$('tr[fl_common=1]').hide(); fl_schat_common = 0;}   break;
       case 1: if (checked) {$('tr[fl_to=1]').show(); fl_schat_to = 1;} else {$('tr[fl_to=1]').hide(); fl_schat_to = 0;}   break;
       case 2: if (checked) {$('tr[fl_pr=1]').show(); fl_schat_pr = 1;} else {$('tr[fl_pr=1]').hide(); fl_schat_pr = 0;}   break;
       case 3: if (checked) {$('tr[fl_to_common=1]').show(); fl_schat_to_common = 1;} else {$('tr[fl_to_common=1]').hide(); fl_schat_to_common = 0;}   break;
     }
}

function doSMStake(v) {
   v=v.replace(/,/gi,'.');
   v=parseFloat(v);
   if (isNaN(v)) {v=0; $('input#sm_stake').val(0);}
   if (v>0) {
        $('input#cb_bots').attr("disabled", "disabled"); $('input#cb_maniac').attr("disabled", "disabled");
        $('td#maniac').addClass("disabled");  $('td#bots').addClass("disabled");
   } else {
        $('input#cb_bots').removeAttr("disabled"); $('input#cb_maniac').removeAttr("disabled");
        $('td#maniac').removeClass();  $('td#bots').removeClass();
  }
}

function tourCaptainAccept(id_game,id_gamer,fl_accept) {
 $.blockUI({message:'<img src="/images/wait_gr.gif" border="0"/>'});
 $.post('?',{jajax:"tour-captain-accept",id_game:id_game,id_gamer:id_gamer,fl_accept:fl_accept},function(xml) {
      $.unblockUI();
//        $("html",xml).text();
  });
}

function doTourRequest(idg) {
  $.blockUI({message:'<img src="/images/wait_gr.gif" border="0"/>'});
 $.post('?',{jajax:"tour-captain-request",id_tour:__id_tour,id_group:idg},function(xml) {
      $.unblockUI();
      html=$("html",xml).text();
      if (html=='ok') {
         alert('Заявка отправлена');
      } else {
         alert('Ошибка постановки заявки в очередь. Уже в очереди?');
      }
  });
}

$(document).ready(function() {    if (__vs=='mf_street') {
/*  if (__id_skin==5) {
    $('body').css('background-color','4D331E');
    $('#id_street_clients').removeClass(); $('#id_street_clients').addClass('bask-id-street-clients');
    $('#id_street_chat').removeClass(); $('#id_street_chat').addClass('bask-id-street-chat');
    $('#id_street_games').removeClass(); $('#id_street_games').addClass('bask-id-street-games');
    $('#id_street_games_active').removeClass(); $('#id_street_games_active').addClass('bask-id-street-games-active');
  }*/


//  street_clients();
  street_chat();
//  street_games();

  setLayout('');
  street_mem_title=document.title;

  $('input#_st_mess').focus();

}});

$(window).resize(function() {  if (__vs=='mf_street') {
  setLayout('');
}});

/**
Vertigo Tip by www.vertigo-project.com
Requires jQuery
*/

this.vtip = function() {    
    this.xOffset = -10; // x distance from mouse
    this.yOffset = 10; // y distance from mouse       
    
    $(".vtip").unbind().hover(    
        function(e) {
            this.t = this.title;
            this.title = ''; 
            this.top = (e.pageY + yOffset); this.left = (e.pageX + xOffset);
            
            $('body').append( '<p id="vtip"><img id="vtipArrow" />' + this.t + '</p>' );
                        
            $('p#vtip #vtipArrow').attr("src", '/images/vtip_arrow.png');

           if ((this.left+$('p#vtip').width())>$(window).width()) {
               this.left=$(window).width()-$('p#vtip').width()-20;
           }

            $('p#vtip').css("top", this.top+"px").css("left", this.left+"px").fadeIn("slow");
            
        },
        function() {
            this.title = this.t;
            $("p#vtip").fadeOut("slow").remove();
        }
    ).mousemove(
        function(e) {
            this.top = (e.pageY + yOffset);
            this.left = (e.pageX + xOffset);
                         
           if ((this.left+$('p#vtip').width())>$(window).width()) {
               this.left=$(window).width()-$('p#vtip').width()-20;
           }

            $("p#vtip").css("top", this.top+"px").css("left", this.left+"px");
        }
    );            
    
};

jQuery(document).ready(function($){vtip();})

function doMFGamesClient(idcl) {
  doMFGames('',0,idcl);
}

function hideMFGamesClient() {
   $("#id_games").animate({
       left: 0, top:0, width:0, height:0, opacity: 'hide'
    }, 500, '', function() {$("#id_games_html").html('');});
}

function doAddModInfo(idcl) {
   txt=$('textarea#cl_info').val();
   location.href="?ta=add_cl_mf_info&redirect=cl_stat="+idcl+'&_i_id_client='+idcl+'&_stid_cl_info='+txt+'&';
}

function doDelModInfo(id,idcl) {
  if (confirm('Удалить свой отзыв об игроке?')) {
     location.href="?ta=del_cl_mf_info&redirect=cl_stat="+idcl+'&_i_id='+id+'&';
  }
}

/*
 * Date Time Picker
 * 
 * author page: http://shuric.dp.ua
 *
 * Copyright (c) 2008-2009 Shuric A. Cornery
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 * version 1.5.1
 * 01/12/2009
 *
 * <div id="id_sugg_dt" onclick="sugg_dt.open();" class="sugg-date"></div>
 *	$_GP['_js'].="var sugg_dt;";
 *	$_GP['_js_ready'].="
 *   sugg_dt = new JsSuggCalendar('id_sugg_dt','sugg_dt',new Date(),true,false,1,'',0,true,false);
 * 	";
 *
 */
function JsSuggCalendar(obj_name,name_var_sugg,dt,fl_time,lm_check,fl_correct,js_on_ok,sec,not_fl_day,dt_from,dt_to,fl_static,fl_to_null) {
  this._nvs=name_var_sugg;
  if (!dt) {var dt = new Date();}
	if (!dt_from) {this.dt_from=false;} else {
	  this.dt_from=dt_from;
		this.dt_from.setSeconds(0);
	}
	if (!dt_to) {this.dt_to=false;} else {
	  this.dt_to=dt_to;
		this.dt_to.setSeconds(0);
	}
	if (!fl_to_null) {
	  this._fl_to_null = false;
	} else {
	  this._fl_to_null = fl_to_null;
	}	
	
	if (dt=='Invalid Date' || isNaN(dt)) {var dt = new Date(0,0,0,0,0); this.fl_date_empty=true;} else {this.fl_date_empty=false;}
	
  this.class_js_day='sugg-dtp-day';
  this.class_js_day_hol='sugg-dtp-day-hol';
  this.class_js_day_now='sugg-dtp-day-now';
  this.class_js_day_tec='sugg-dtp-day-tec';
	this.class_js_day_gray='sugg-dtp-day-gray';
  
	this._fl_kvartal=false;
	
	this._ua_holidays = new Array(
	  '0101','0701','0803','0105','0205','0905','2806','2408'
	);
	this.fl_holidays = 'ua';
	
  this._dt = dt;
	this._fl_static=fl_static;
  this._js_year = dt.getFullYear();
  this._js_month = dt.getMonth()+1;
  this._js_day = dt.getDate();
  this._js_hour = dt.getHours();
  this._js_min = dt.getMinutes();
	this._top_year = this._js_year; 
	this._top_month = this._js_month; 
	
  this._js_year_1 = this._js_year;
  this._js_month_1 = this._js_month;
  this._js_day_1 = this._js_day;
  this._js_hour_1 = this._js_hour;
  this._js_min_1 = this._js_min;
	
  this._fl_time = fl_time;
	if (not_fl_day) {this._fl_day = false;} else {this._fl_day=true;}
  this._sel_day = '';
  this._lm = lm_check;
  this._fl_open = false;
  this._fl_correct_lm = fl_correct; // 1 - другую дату, 0 - себя, -1 - никого
  this._js_on_ok=js_on_ok;
  this._js_on_open='';
  this._js_on_change_dt_more = '';
  this._js_on_change_dt_less = '';
  this._js_on_change_dt_self = '';
  this._js_after_change_month_func_name = '';
  this._js_on_day_func_name = ''; // function(year,month,day)
  this._href_on_day_func_name = ''; // 
  this._position = 'rb'; // rb, rt, lt, lb
  this._pos_delta_x = 0;
  this._pos_delta_y = 0;
  this._fl_change = false;
  this._dt_open = '';
	
	this._ar_day_click = new Array();
	this._ar_day_title = new Array();
	this._fl_day_click = false;
  
  this.prefix_draw_before='';
  this.prefix_draw_after='';
  
  if (!sec) sec=0;  this._dt.setSeconds(0);
  
  this._sugg_more=null;
  this._sugg_less=null;
  
	if (this._fl_static) {
		$('#'+obj_name).html('<div id="id_calendar_'+obj_name+'"></div>');
	} else {
    $('body').append('<div id="id_calendar_'+obj_name+'" style="position:absolute;z-index:10000;top:0px;left:0px; background-color:white;"></div>');
	}
	
	this._obj_calendar=$('#'+'id_calendar_'+obj_name);
  //this._obj_calendar=document.all?document.all['id_calendar_'+obj_name]:document.getElementById('id_calendar_'+obj_name);
  
	this._obj_dt=$('#'+obj_name);
	//document.all?document.all[obj_name]:document.getElementById(obj_name);
  
  this.l2sz2 = function(i) {
	  i=parseInt(i); 
		if (i<10) {return '0'+i;} else {return i;}
	}

  this.parseInt0 = function(i) {
	  i=String(i).replace(/^0+/,"");
	  if (i=='') {return 0;} else {return parseInt(i);}
	}

	this.isHoliday = function(d,m,y) {
	  tdate = new Date(y,m-1,d);
		w = tdate.getDay();
		if (w==0 || w==6) return true;
	  switch (this.fl_holidays) {
		  case 'ua':
//_debug(this.l2sz2(d)+''+this.l2sz2(m));			
			  if ($.inArray((this.l2sz2(d)+''+this.l2sz2(m)),this._ua_holidays)>-1) {return true;}
			break;
		}
		return false;
	}
	
  this.getDateSQL = function() {return this._js_year+'-'+this.l2sz2(this._js_month)+'-'+this.l2sz2(this._js_day)+' '+this.l2sz2(this._js_hour)+':'+this.l2sz2(this._js_min)+':00';}
  this.getDateWithoutTimeSQL = function() {return this._js_year+'-'+this.l2sz2(this._js_month)+'-'+this.l2sz2(this._js_day);}
  this.getDateDMYHI = function() {
  	s=this.l2sz2(this._js_day)+'.'+this.l2sz2(this._js_month)+'.'+this._js_year;
  	if (this._fl_time) {
  		s+=' '+this.l2sz2(this._js_hour)+':'+this.l2sz2(this._js_min);
  	}
  	return s;
  }
  this.getDateDMYHI_pba =function() {
    s=this.getDateDMYHI();
    if (this.prefix_draw_before!='') {s=this.prefix_draw_before+s;}
    if (this.prefix_draw_after!='') {s=s+this.prefix_draw_after;}
    return s;
  }
	
	this.setDayClick = function(year,month,sday) {
		this._fl_day_click = true;
	  year=parseInt(year); 
	  month=parseInt(month); 
	  if (!this._ar_day_click[year]) this._ar_day_click[year]=new Array();
	  if (!this._ar_day_click[year][month]) this._ar_day_click[year][month]=new Array();
	  if (!this._ar_day_title[year]) this._ar_day_title[year]=new Array();
	  if (!this._ar_day_title[year][month]) this._ar_day_title[year][month]=new Array();
	  ar_day=sday.split('|');
		for (i=0; i<ar_day.length; i++) {
		  ar1=ar_day[i].split(':'); 
		  day=parseInt(ar1[0]); 
	    this._ar_day_click[year][month][day]=true;
	    this._ar_day_title[year][month][day]=ar1[1];
		}	
		this._drawSuggestCalendar(this._top_year,this._top_month,-1,-1,-1);
	}
	
	this.checkDayClick = function(year,month,day) {
	  if (this._ar_day_click[year] && this._ar_day_click[year][month] && this._ar_day_click[year][month][day]) {
		  return true;
		} else {
		  return false;
		}
	}
  
  this.open = function(mousex,mousey) {
//	  var mousex=(slider.ie4||slider.ie5)?event.clientX+document.body.scrollLeft:e.pageX;
// 	  var mousey=(slider.ie4||slider.ie5)?event.clientY+document.body.scrollTop:e.pageY;
//    if (mousexy) mousex=mousexy.x;
//    if (mousexy) mousey=mousexy.y;
//    if (this._position=='rt') {x=mousex; y=mousey-170;} else {x=mousex; y=mousey;}
    if (!this._fl_static) {
      if (!mousex && mousexy) {mousex=mousexy.x;}
      if (!mousey && mousexy) {mousey=mousexy.y;}
      if ((mousex+170)>$(window).width()) {mousex=mousex-170;}
      if ((mousey+210)>$(window).height()) {mousey=mousey-210;}
      if (mousex<10) mousex=10; if (mousey<10) mousey=10;
      mousex+=this._pos_delta_x; mousey+=this._pos_delta_y;
      this._obj_calendar.css({left:mousex,top:mousey});
		}	
    this._obj_calendar.show();
		if (this.fl_date_empty) {
			dt = new Date();
			this._js_year = dt.getFullYear();
			this._js_month = dt.getMonth()+1;
			this._js_day = dt.getDate();
			this._js_hour = dt.getHours();
			this._js_min = dt.getMinutes();
		}	 else {
		  dt=new Date(this._js_year,this._js_month-1,this._js_day,this._js_hour,this._js_min);
		}
		if (this.dt_from && dt<this.dt_from) {this.setDate(this.dt_from);}
		if (this.dt_to && dt>this.dt_to) {this.setDate(this.dt_to);}
    this._drawSuggestCalendar(this._js_year,this._js_month,this._js_day,this._js_hour,this._js_min);
    this._fl_open=true;
    this._dt_open=this.getDateSQL();
    if (this._js_on_open!='') {eval(this._js_on_open);}
		this._jsAfterChangeMonth();
  }
	
  this.setPosition = function(spos, delta_x, delta_y) {
    this._position=spos; this._pos_delta_x=delta_x; this._pos_delta_y=delta_y;
  }
  
  this._checkDate = function() {
    if (this._sugg_more) {
      if (this._dt.getTime()>this._sugg_more._dt.getTime()-1000*this._lm*60) {
         switch (this._fl_correct_lm) {
           case 1: 
             dt2=new Date(); dt2.setTime(this._dt.getTime()+1000*this._lm*60); this._sugg_more.setDate(dt2); 
             if (this._js_on_change_dt_more!='') {eval(this._js_on_change_dt_more);}
           break;
           case 0: 
             dt2=new Date(); dt2.setTime(this._sugg_more._dt.getTime()-1000*this._lm*60); this.setDate(dt2); 
             if (this._js_on_change_dt_self!='') {eval(this._js_on_change_dt_self);}
           break;
         }
//alert('0:'+dt2+this._sugg_more._dt+this._nvs+' '+dt2);
      }
    }
    if (this._sugg_less) {
      if (this._dt.getTime()<this._sugg_less._dt.getTime()+1000*this._lm*60) {
         switch (this._fl_correct_lm) {
           case 1: 
             dt2=new Date(); dt2.setTime(this._dt.getTime()-1000*this._lm*60); this._sugg_less.setDate(dt2); 
             if (this._js_on_change_dt_less!='') {eval(this._js_on_change_dt_less);}
           break;
           case 0: 
             dt2=new Date(); dt2.setTime(this._sugg_less._dt.getTime()+1000*this._lm*60); this.setDate(dt2); 
             if (this._js_on_change_dt_self!='') {eval(this._js_on_change_dt_self);}
           break;
         }
      }
    }
  }
  
  this._drawIDDate = function(fl_cancel) {
	  if (!this._fl_static) {
			if (this.fl_date_empty) {
				this._obj_dt.html('');
				return;
			}
		
			if (!fl_cancel) {
				yy=this._js_year;
				mm=this.l2sz2(parseInt(this._js_month))
				dd=this.l2sz2(this._js_day);
				if (this._fl_time) {
					hh=this.l2sz2(this._js_hour);
					ii=this.l2sz2(this._js_min);
				}
			} else {
				yy=this._js_year_1;
				mm=this.l2sz2(parseInt(this._js_month_1));
				dd=this.l2sz2(this._js_day_1);
				if (this._fl_time) {
					hh=this.l2sz2(this._js_hour_1);
					ii=this.l2sz2(this._js_min_1);
				}
			}
			
			if (this._fl_kvartal) {
			  s=Math.round((mm-1)/3+1)+' кв. '+yy;
				s1=dd+'.'+mm+'.'+yy;
			} else {
				if (this._fl_day) {
					s=dd+'.'+mm+'.'+yy;
//_debug('['+this.parseInt0(dd)+' '+this.parseInt0(mm)+']');
					if (this.isHoliday(this.parseInt0(dd),this.parseInt0(mm),this.parseInt0(yy))) {
					  this._obj_dt.addClass('sugg-dtp-holiday');
					} else {
					  this._obj_dt.removeClass('sugg-dtp-holiday');
					}
					if (this._fl_time) {s=s+' '+hh+':'+ii;}
				} else {
					s=mm+'.'+yy;
				}
			}
			if (this.prefix_draw_before!='') {s=this.prefix_draw_before+s;}
			if (this.prefix_draw_after!='') {s=s+this.prefix_draw_after;}
			if (this._obj_dt.attr('tagName')=='INPUT') {
				this._obj_dt.val(s);
				if (this._fl_kvartal) {
					this._obj_dt.attr('tvalue',s1);
				}
			} else {
				if (jQuery.browser.msie) {
					this._obj_dt.html(s+'&'+'nbsp'+';');
				} else {
					this._obj_dt.html('<nobr>'+s+'&nbsp;</nobr>');
				}
				this._obj_dt.css({cursor:'pointer'});
			}
		}
  }
  
  this._drawIDDate();
	
	this._checkDTFromTo = function(dt) {
    if (this._fl_day) {
			if (this._fl_time) {
				dtf = dt;
				dtt = dt;
			} else {
				dtf = new Date(dt.getFullYear(),dt.getMonth(),dt.getDate(),23,59,59);
				dtt = new Date(dt.getFullYear(),dt.getMonth(),dt.getDate(),0,0,0);
			}
		} else {
			dtf = new Date(dt.getFullYear(),dt.getMonth(),30,23,59,59);
			dtt = new Date(dt.getFullYear(),dt.getMonth(),1,0,0,0);
		}
//_debug(dt+' from='+dtf+' to='+dtt+' == from='+this.dt_from+' == to='+this.dt_to+' <br> ');
		if ((!this.dt_from || (this.dt_from && dtf>=this.dt_from)) &&
				(!this.dt_to || (this.dt_to && dtt<=this.dt_to)))
		{
		  return 0;
		} else {
		  if (this.dt_from && dtf<this.dt_from) {
			  return -1;
			} else {
			  return 1;
			}
		}
	}

  this.setDate = function(dt) {
	  if (!dt) {var dt = new Date();}
    this._js_year = dt.getFullYear();
		if (this._top_month!=(dt.getMonth()+1)) {fl_change_month = true;} else {fl_change_month = false;}
    this._js_month = dt.getMonth()+1;
    this._js_day = dt.getDate();
    this._js_hour = dt.getHours();
    this._js_min = dt.getMinutes();
//_debug(dt);		
		if (this._checkDTFromTo(dt)==0) {
			this._top_year = this._js_year; 
    	this._top_month = this._js_month; 

			this._dt = dt;
			this._drawIDDate();
			if (this._fl_open) {this._redraw();}
			
			if (fl_change_month) this._jsAfterChangeMonth();
		}
//    this._dt = new Date(this._js_year,this._js_month-1,this._js_day,this._js_hour,this._js_min,0);
  }
  
  this.incDay = function(inc) {
  	if (inc!=0) {d=this._dt; tm=d.getTime(); d.setTime(tm+inc*1000*60*60*24); this.setDate(d);}
  }
  
  this.setDateFormat = function(sdt,fmt) {
    re1 = /^\s*/;  re2 = /\s*$/;   sdt=sdt.replace(re1, "").replace(re2, "");
		d=0; m=0; y=0; h=0; i=0; s=0;
		for (ii=0; ii<fmt.length; ii++) {
		  if (ii<sdt.length) {
				v=parseInt(sdt.charAt(ii)); f=fmt.charAt(ii);
				if (f=='d') d=d*10+v;
				if (f=='y') y=y*10+v;
				if (f=='m') m=m*10+v;
				if (f=='h') h=h*10+v;
				if (f=='i') i=i*10+v;
				if (f=='s') s=s*10+v;
	      if (isNaN(d) || isNaN(m) || isNaN(y) || isNaN(h) || isNaN(i) || isNaN(s)) return false;
   	  }
		}
		d = new Date(y,m-1,d,h,i,s);
    if (d!=null) {this.setDate(d);}
  }
  
  this._close = function() {
    this._obj_calendar.html(''); this._obj_calendar.hide();
    this._fl_open=false; 
  }
	
  this.ok_empty = function() {
	  if (!this._fl_static) {
			if (this._obj_dt.attr('tagName')=='INPUT') {
				this._obj_dt.val('');
				if (this._fl_kvartal) {
					this._obj_dt.attr('tvalue','');
				}
			} else {
				this._obj_dt.html('NULL');
			}	
			this._close();
		}
	}
	
  this.ok = function() {
		this.fl_date_empty=false;
	  if (!this._fl_day) {
		  this._js_year=this._top_year;
			this._js_month=this._top_month;
		  dt = new Date(this._js_year,this._js_month-1,1);
		} else {
			dt = new Date(this._js_year,this._js_month-1,this._js_day,this._js_hour,this._js_min,0);
		}
  	if (this._checkDTFromTo(dt)==0) {
			this._js_year_1 = this._js_year;
			this._js_month_1 = this._js_month;
			this._js_day_1 = this._js_day;
			this._js_hour_1 = this._js_hour;
			this._js_min_1 = this._js_min;
			this._close();
			this._drawIDDate(true);
		}
  }
	
  this.cancel = function() {
	  this._close();
		this._fl_change=false;
		this._drawIDDate(true);
  }
  
  this.closee = function() {this._fl_change=false;}
  
  this._setIDDate = function (year,month,day) {
    if (year!=-1 && month!=-1 && day!=-1) {
      this._js_year=year;  this._js_month=month;  this._js_day=day;
    }
    //if (this._fl_time) {if (year!=-1) {this._deltaTime(-1,0);}}
    this._dt = new Date(this._js_year,this._js_month-1,this._js_day,this._js_hour,this._js_min,0);
    this._checkDate();
    this._drawIDDate();
    if (this._dt_open!=this.getDateSQL()) {this._fl_change=true;}
  }
  
  this._changeDay = function(year,month,day) {
    this._setIDDate(year,month,day);
		if (this._js_on_day_func_name!='' && this.checkDayClick(year,month,day)) {
		   eval(this._js_on_day_func_name+'('+year+','+month+','+day+');');
		}
    if (this._fl_time) {
      dt = new Date(this._js_year,this._js_month-1,this._js_day,this._js_hour,this._js_min,0);
			code=this._checkDTFromTo(dt);
			if (code!=0) {
			  if (code==-1 && this.dt_from) {
					$('#'+this._nvs+'_js_id_hour_1').html(Math.floor(this.dt_from.getHours()/10));
					$('#'+this._nvs+'_js_id_hour_2').html(this.dt_from.getHours()%10);
					$('#'+this._nvs+'_js_id_min_1').html(Math.floor(this.dt_from.getMinutes()/10));
					$('#'+this._nvs+'_js_id_min_2').html(this.dt_from.getMinutes()%10);
					this._js_hour=this.dt_from.getHours();
					this._js_min=this.dt_from.getMinutes();
				}
				if (code==1 && this.dt_to) {
					$('#'+this._nvs+'_js_id_hour_1').html(Math.floor(this.dt_to.getHours()/10));
					$('#'+this._nvs+'_js_id_hour_2').html(this.dt_to.getHours()%10);
					$('#'+this._nvs+'_js_id_min_1').html(Math.floor(this.dt_to.getMinutes()/10));
					$('#'+this._nvs+'_js_id_min_2').html(this.dt_to.getMinutes()%10);
					this._js_hour=this.dt_to.getHours();
					this._js_min=this.dt_to.getMinutes();
				}
			}
		}
    this._drawSuggestCalendar(this._js_year,this._js_month,this._js_day,-1,-1);
  }  
	
	this.viewAsKvartal = function() {
	  this._fl_kvartal = true;
    this._js_day = 1;
    this._js_hour = 0;
    this._js_min = 0;
		this._drawIDDate();
	}

  this._changeMonth = function(year,month) {
	  dt1=new Date(year,month,1);
		err=false;
		if (this.dt_from) {
			dtf=new Date(this.dt_from.getFullYear(),this.dt_from.getMonth()+1,1);
			if (dt1<dtf) err=true;
		}
		if (this.dt_to) {
			dtt=new Date(this.dt_to.getFullYear(),this.dt_to.getMonth()+1,1);
			if (dt1>dtt) err=true;
		}	
		if (!err) {
			this._top_year = year; 
    	this._top_month = month; 
			this._drawSuggestCalendar(year,month,-1,-1,-1);
			this._jsAfterChangeMonth();
		}
  }  
	
	this._jsAfterChangeMonth = function() {
		if (this._js_after_change_month!='') {
			eval(this._js_after_change_month_func_name+'('+this._top_year+','+this._top_month+');');
		}    
	}
	
  this._redraw = function() {
    this._drawSuggestCalendar(this._js_year,this._js_month,this._js_day,this._js_hour,this._js_min);
  }
  
  this._drawSuggestCalendar = function(year,month,day,hour,min) {
//    _sel_day=year+''+this.l2sz2(month-1)+''+this.l2sz2(day);
		_sel_day=this._js_year+''+this.l2sz2(this._js_month-1)+''+this.l2sz2(this._js_day);
    tdate = new Date();
    ordinal_day_now = tdate.getFullYear()+''+this.l2sz2(tdate.getMonth())+''+this.l2sz2(tdate.getDate());
    
    tdate = new Date(year,month-1,1);
    
    y_prev=year; m_prev=month-1; if (m_prev==0) {m_prev=12; y_prev=year-1;}
    y_next=year; m_next=month+1; if (m_next==13) {m_next=1; y_next=year+1;}
    
    day_start=tdate.getDay(); if (day_start==0) {day_start=7;} day_start=day_start-1;
    switch (month) {
      case 4:
      case 6:
      case 9:
      case 11: days=30; break;
      case 2: if (((year%4)==0) && ((year%100)!=0) || ((year%400)==0)) {days=29;} else {days=28;} break;
      default: days=31;
    }
//    if (month<10) {month='0'+month;}
  
    html='';
    
    html+='<TABLE BORDER="0" CELLSPACING="1" CELLPADDING="2" class="sugg-dtp">';
    html+='<tr><td class="sugg-dtp-close" onclick="'+this._nvs+'.setDate();" title="текущее">&#149;</td>';
		html+='<td colspan="5" align="center"><table border="0"><tr><td>';
		if (this._fl_kvartal) {
			html+='<td class="cp" onclick="'+this._nvs+'._changeMonth('+(year-1)+','+month+','+day+');">&lt;</td>';
			html+='<TD ALIGN="center">'+year+'</td>';
			html+='<td class="cp" onclick="'+this._nvs+'._changeMonth('+(year+1)+','+month+','+day+');">&gt;</td>';
		} else {
			html+='<td class="cp" onclick="'+this._nvs+'._changeMonth('+y_prev+','+m_prev+','+day+');">&lt;</td>';
			html+='<TD ALIGN="center">'+this.l2sz2(month)+'.'+year+'</td>';
			html+='<td class="cp" onclick="'+this._nvs+'._changeMonth('+y_next+','+m_next+','+day+');">&gt;</td>';
		}
		html+='</td></tr></table></td>';
	  if (this._fl_static) {
			html+='<td></td>';
		} else {
			html+='<td class="sugg-dtp-close" onclick="'+this._nvs+'.cancel();" title="отменить">&#215;</td>';
		}
		html+='</tr>';
		
		if (this._fl_kvartal) {
//cl='sugg-dtp-day-tec';		
//alert(_sel_day);		
			html+='<tr><td height="5"></td><td></td><td></td><td></td><td></td><td></td><td></td></TR>';
			html+='<tr class="sugg-dtp-title"><td colspan="3">квартал: </td>';
			i=1;
			while (i<=10) {
				if (_sel_day==year+''+this.l2sz2(i-1)+'01') {
					cl='sugg-dtp-day-tec';
				} else {
					cl='sugg-dtp-day';
				}
				html+='<td onclick="'+this._nvs+'._changeDay('+year+','+i+',1);" class="'+cl+'">'+Math.ceil(i/3) +'</td>';
			  i+=3;
			}
			html+='</TR>';
			html+='<tr><td colspan="7" height="5"></td></tr>';
		} else {
			if (this._fl_day) {
				html+='<tr class="sugg-dtp-title"><td>Пн</td><td>Вт</td><td>Ср</td><td>Чт</td><td>Пт</td><td class="sugg-dtp-holiday">Сб</td><td class="sugg-dtp-holiday">Вс</td></TR>';
				tday=0;
				tec_day=1;
				html+='<tr>';
				for (i=0;i<day_start;i++) {html+='<td></td>'; tday++;}
				for (tec_day=1; tec_day<=days; tec_day++) {
					if ((tday%7)==0) {
						if (day_start=0) {html+='<tr>';} else {html+='</tr><tr>';};
					}
					dttecf=new Date(year,month-1,tec_day,23,59,59);
					dttect=new Date(year,month-1,tec_day,0,0,0);
					oncl='';
					if ((!this.dt_from || (this.dt_from && dttecf>=this.dt_from)) &&
							(!this.dt_to || (this.dt_to && dttect<=this.dt_to)) &&
							(!this._fl_day_click || (this._fl_day_click && this.checkDayClick(year,month,tec_day))) 
						 )
					{
						html+='<td onclick="'+this._nvs+'._changeDay('+year+','+month+','+tec_day+');" ';
						cl='sugg-dtp-day';
						if (this.isHoliday(tec_day,month,year)) {cl='sugg-dtp-day-hol';}
						if (ordinal_day_now==tdate.getFullYear()+''+this.l2sz2(tdate.getMonth())+''+this.l2sz2(tec_day)) {cl='sugg-dtp-day-now';}
						if (_sel_day==tdate.getFullYear()+''+this.l2sz2(tdate.getMonth())+''+this.l2sz2(tec_day)) {cl='sugg-dtp-day-tec';}
						if (this._fl_day_click && this.checkDayClick(year,month,tec_day)) {
							html+=' title="'+this._ar_day_title[year][month][tec_day]+'"';
	//  				  oncl='onclick="'+this._nvs+'._changeDay('+year+','+month+','+tec_day+'); return false;"';
							oncl='onclick="return false;"';
						}
					} else {
						html+='<td ';
						cl='sugg-dtp-day-gray';
					}
					if (this._href_on_day_func_name!='' && oncl!='') {
						s_day='<a class="'+cl+'" '+oncl+' href="?'+this._href_on_day_func_name+'&year='+year+'&month='+month+'&day='+tec_day+'">'+tec_day+'</a>';
					} else {
						s_day=tec_day;
					}
					html+='class="'+cl+'">'+s_day+'</td>';
					tday++;
				}
				html+='</tr>';
				
				if (this._fl_time) {
					if (hour==-1) {hour=this._js_hour;}
					if (min==-1) {min=this._js_min;}
					html+='<tr>';
					html+='<td colspan="7" align="center">';
						html+='<table border="0" cellpadding="0" cellspacing="0" class="sugg-dtp-time">';
						html+='<tr valign="bottom">';
						html+='<td></td>';
						html+='<td class="sugg-dtp-arrows" onclick="'+this._nvs+'._deltaTime(1,1);">&#9650;</td><td class="sugg-dtp-arrows" onclick="'+this._nvs+'._deltaTime(2,1);">&#9650;</td>';
						html+='<td></td>';
						html+='<td class="sugg-dtp-arrows" onclick="'+this._nvs+'._deltaTime(3,1);">&#9650;</td><td class="sugg-dtp-arrows" onclick="'+this._nvs+'._deltaTime(4,1);">&#9650;</td>';
						html+='<td></td>';
						html+='</tr>';
						html+='<tr>';
						html+='<td class="sugg-dtp-time-hm" align="right" style="padding-right:3px;" onclick="'+this._nvs+'._deltaTime(1,0);'+this._nvs+'._deltaTime(2,0);">час</td>';
						html+='<td class="sugg-dtp-time-hm" id="'+this._nvs+'_js_id_hour_1" onclick="'+this._nvs+'._deltaTime(1,0);">'+Math.floor(hour/10)+'</td>';
						html+='<td class="sugg-dtp-time-hm" id="'+this._nvs+'_js_id_hour_2" onclick="'+this._nvs+'._deltaTime(2,0);">'+(hour%10)+'</td>';
						html+='<td>:</td>';
						html+='<td class="sugg-dtp-time-hm" id="'+this._nvs+'_js_id_min_1" onclick="'+this._nvs+'._deltaTime(3,0);">'+Math.floor(min/10)+'</td>';
						html+='<td class="sugg-dtp-time-hm" id="'+this._nvs+'_js_id_min_2" onclick="'+this._nvs+'._deltaTime(4,0);">'+(min%10)+'</td>';
						html+='<td class="sugg-dtp-time-hm" style="padding-left:3px;"  onclick="'+this._nvs+'._deltaTime(3,0);'+this._nvs+'._deltaTime(4,0);">мин</td>';
						html+='</tr>';
						html+='<tr valign="top">';
						html+='<td></td>';
						html+='<td class="sugg-dtp-arrows" onclick="'+this._nvs+'._deltaTime(1,-1);">&#9660;</td><td class="sugg-dtp-arrows" onclick="'+this._nvs+'._deltaTime(2,-1);">&#9660;</td>';
						html+='<td></td>';
						html+='<td class="sugg-dtp-arrows" onclick="'+this._nvs+'._deltaTime(3,-1);">&#9660;</td><td class="sugg-dtp-arrows" onclick="'+this._nvs+'._deltaTime(4,-1);">&#9660;</td>';
						html+='<td></td>';
						html+='</tr>';
						html+='</table>';
					html+='</td>';
					html+='</tr>';
				}
			}
		}
	  if (!this._fl_static) {
			html+='<tr>';
			if (this._fl_to_null) {
				html+='<td colspan="1" class="sugg-dtp-close" onclick="'+this._nvs+'.ok_empty(); '+this._js_on_ok+'; '+this._nvs+'.closee();" title="сбросить">&Theta;</td>';
				cs=6;
			} else {
			  cs=7;
			}
			html+='<td colspan="'+cs+'" class="sugg-dtp-close" onclick="'+this._nvs+'.ok(); '+this._js_on_ok+'; '+this._nvs+'.closee();" title="запомнить">ok</td>';
			html+='</tr>';
		}	
    
    html+="</TABLE>";
//alert(html);    
    this._obj_calendar.html(html);
		
    // this._obj_calendar.className='show'; this._obj_calendar.style.visibility='visible';
    
  }
  
  this._deltaTime = function(tp,delta) {
    if (this._fl_time) {
      fl_time=true;
			h1=parseInt($('#'+this._nvs+'_js_id_hour_1').html());
			h2=parseInt($('#'+this._nvs+'_js_id_hour_2').html());
			m1=parseInt($('#'+this._nvs+'_js_id_min_1').html());
			m2=parseInt($('#'+this._nvs+'_js_id_min_2').html());
      switch (tp) {
        case 1: 
           h1+=delta;
           if (delta>0) {if (h1>2) {h1=0;}}
           if (delta<0) {if (h1<0) {h1=2;}}
           if (delta==0) {h1=0;}
           $('#'+this._nvs+'_js_id_hour_1').html(h1);
           if (h1==2 && h2>3) {h2=3; $('#'+this._nvs+'_js_id_hour_2').html(h2);}
        break;   
        case 2: 
           h2+=delta;
           if (delta>0) {if (h2>9) {h2=0; if (h1<2) {h1++; $('#'+this._nvs+'_js_id_hour_1').html(h1);}}}
           if (delta<0) {if (h2<0) {h2=9; if (h1>0) {h1=h1-1;} else {h2=3; h1=2;} $('#'+this._nvs+'_js_id_hour_1').html(h1);}}
           if (delta==0) {h2=0;}
           if (h1==2 && h2>3) {h1=0; $('#'+this._nvs+'_js_id_hour_1').html(h1); h2=0;}
           $('#'+this._nvs+'_js_id_hour_2').html(h2);
        break;
        case 3: 
           m1+=delta;
           if (delta>0) {if (m1>5) {m1=0;}}
           if (delta<0) {if (m1<0) {m1=5;}}
           if (delta==0) {m1=0;}
           $('#'+this._nvs+'_js_id_min_1').html(m1);
        break;   
        case 4: 
           m2+=delta;
           if (delta>0) {if (m2>9) {m2=0; if (m1<5) {m1++;} else {m1=0;} $('#'+this._nvs+'_js_id_min_1').html(m1);}}
           if (delta<0) {if (m2<0) {m2=9; if (m1>0) {m1=m1-1;} else {m1=5;} $('#'+this._nvs+'_js_id_min_1').html(m1);}}
           if (delta==0) {m2=0;}
           $('#'+this._nvs+'_js_id_min_2').html(m2);
        break;   
      }
      if (m1==0) {this._js_min=m2;} else {this._js_min=parseInt(m1+''+m2);}
      if (h1==0) {this._js_hour=h2;} else {this._js_hour=parseInt(h1+''+h2);}
      dt = new Date(this._js_year,this._js_month-1,this._js_day,this._js_hour,this._js_min,0);
			code=this._checkDTFromTo(dt);
			if (code==0) {
				this._dt = dt;
				this._checkDate();
				this._drawIDDate();
				if (this._dt_open!=this.getDateSQL()) {this._fl_change=true;}
			} else {
			  if (code==-1) {
				  if (this.dt_from) {
						$('#'+this._nvs+'_js_id_hour_1').html(Math.floor(this.dt_from.getHours()/10));
						$('#'+this._nvs+'_js_id_hour_2').html(this.dt_from.getHours()%10);
						$('#'+this._nvs+'_js_id_min_1').html(Math.floor(this.dt_from.getMinutes()/10));
						$('#'+this._nvs+'_js_id_min_2').html(this.dt_from.getMinutes()%10);
						this._js_hour=this.dt_from.getHours();
						this._js_min=this.dt_from.getMinutes();
					}
				} else {
				  if (this.dt_to) {
						$('#'+this._nvs+'_js_id_hour_1').html(Math.floor(this.dt_to.getHours()/10));
						$('#'+this._nvs+'_js_id_hour_2').html(this.dt_to.getHours()%10);
						$('#'+this._nvs+'_js_id_min_1').html(Math.floor(this.dt_to.getMinutes()/10));
						$('#'+this._nvs+'_js_id_min_2').html(this.dt_to.getMinutes()%10);
						this._js_hour=this.dt_to.getHours();
						this._js_min=this.dt_to.getMinutes();
					}
				}
			}
    }
  }
  
};

function checkDate(s,fmt) {
// fmt='yyyy-mm-dd hh:ii:ss';  
	 yy=''; mm=''; dd=''; hh=''; ii=''; ss='';
	 if (fmt.length!=s.length) {return false;}
	 for (i=0; i<fmt.length; i++) {
		 if (i<s.length) {
			 char1=s.charAt(i);
			 charF=fmt.charAt(i);
			 switch (charF) {
				 case 'y':yy=yy+char1; if (!itInt(char1)) {return false;} break;
				 case 'm':mm=mm+char1; if (!itInt(char1)) {return false;} break;
				 case 'd':dd=dd+char1; if (!itInt(char1)) {return false;} break;
				 case 'h':hh=hh+char1; if (!itInt(char1)) {return false;} break;
				 case 'i':ii=ii+char1; if (!itInt(char1)) {return false;} break;
				 case 's':ss=ss+char1; if (!itInt(char1)) {return false;} break;
				 default: if (char1!=charF) {return false;}
			 }
		 } else {return false;}  
	 }
	 
	 yy=parseInt(sh_trim_to_int_without_zero(yy));
	 dd=parseInt(sh_trim_to_int_without_zero(dd));
	 mm=parseInt(sh_trim_to_int_without_zero(mm));
	 hh=parseInt(sh_trim_to_int_without_zero(hh));
	 ii=parseInt(sh_trim_to_int_without_zero(ii));
	 ss=parseInt(sh_trim_to_int_without_zero(ss));
	 
	 if (mm>12 || mm<1) {return false;}
	 if (hh>59 || hh<1) {return false;}
	 if (ii>59 || ii<1) {return false;}
	 if (ss>99 || ss<1) {return false;}
	 if (yy<1) {return false;}
	 
	 if (mm==2) {
		 maxday=28;
		 if (yy%400==0 || (yy%4==0 && yy%100>0)) maxday=29;
	 } else {
		 maxday=31;
		 if (mm==2) maxday=28; 
		 if (mm==4 || mm==6 || mm==9 || mm==11) maxday=30; 
	 }
	 if (dd>maxday) return false;  

	 return true;
}

/*
div.sugg-dtp {margin-bottom:3px; border-bottom:1px dashed #0D7C50; color:#0D7C50;}
input.sugg-dtp-holiday, div.sugg-dtp-holiday {color:red;}

table.sugg-dtp {width:100%; border:1px solid #dddddd; padding:2px; font-size:11px;}
tt.sugg-dtp-title {font-weight:bold; text-align:center;}
td.sugg-dtp-holiday {color:red;}
td.sugg-dtp-time-hm {cursor:crosshair; text-align:center;}
table.sugg-dtp-time {font-size:12px;}
td.sugg-dtp-arrows {cursor:crosshair; font-size:8px; text-align:center;}
td.sugg-dtp-close {cursor:pointer; font-size:13px; background-color:#eeeeee; text-align:center;}

td.sugg-dtp-day{background-color:#f7f7f7;cursor:pointer;text-align:center;border:1px solid white; color:black;}
td.sugg-dtp-day:hover{border:1px dotted #006600;background-color:#f0f0f0;}
a.sugg-dtp-day {text-decoration:none; color:black;}

td.sugg-dtp-day-hol{background-color:#f7f7f7;cursor:pointer;text-align:center;color:red;}
td.sugg-dtp-day-hol:hover{border:1px dotted #006600;background-color:#f0f0f0;}
a.sugg-dtp-day-hol {text-decoration:none; color:red;}

td.sugg-dtp-day-now{background-color:#f7f7f7;cursor:pointer;text-align:center;border:1px solid #FFD700;}
td.sugg-dtp-day-now:hover{border:1px dotted #006600;background-color:#f0f0f0;}
a.sugg-dtp-day-now{text-decoration:none; }

td.sugg-dtp-day-tec{background-color:#f7f7f7;cursor:pointer;text-align:center;border:1px solid #777777;}
a.sugg-dtp-day-tec {text-decoration:none; }

td.sugg-dtp-day-gray {background-color:#f0f0f0; cursor:default; text-align:center; border:1px solid white; color:#bbbbbb;}
a.sugg-dtp-day-gray {text-decoration:none; color:#bbbbbb;}
*/

var _isugg = 0;
var _fl_sugg_open = false;
var _fl_sugg_mo = false;
var _fl_sugg_run = false;
var _fl_sugg_add = false;
var _ms_sugg_prev = 0;
//var _tid = 0;
var _ar_sugg = new Array();
var _fl13 = false;
var _isugg_cache = new Array();

function _addArSuggest(sg) {
  for (i=0; i<_ar_sugg.length; i++) {if (_ar_sugg[i]==sg) return true;} 
  _ar_sugg.splice(_ar_sugg, 0, sg); return true;
}

//function doSetSuggestFind(fn,w,s) {
//  eval('s1=document.'+fn+'.'+w+'.value;'); 
//  n1=s1.lastIndexOf(' ');  
//  n2=s1.lastIndexOf(',');  
//  n3=s1.lastIndexOf(';');  
//  n4=s1.lastIndexOf('|');  
//  n=Math.max(Math.max(n1,n2),Math.max(n3,n4));
//  if (n>0) {s=s1.substring(0,n+1)+s;} 
//  eval('document.'+fn+'.'+w+'.value=s;');  
//  hideSuggest(w);
//}

function setSuggestToInput(fn,w,prefix,i) {
  obj=document.all?document.all[prefix+'_isugg_b_'+i]:document.getElementById(prefix+'_isugg_b_'+i);
  if (obj) {
    s=obj.innerHTML;
    if (_fl_sugg_add) {
      eval('s1=document.'+fn+'.'+w+'.value;'); 
      n1=s1.lastIndexOf(' ');  
      n2=s1.lastIndexOf(',');  
      n3=s1.lastIndexOf(';');  
      n4=s1.lastIndexOf('|');  
      n=Math.max(Math.max(n1,n2),Math.max(n3,n4));
      if (n>0) {s=s1.substring(0,n+1)+s;} 
    }
    eval('document.'+fn+'.'+w+'.value=s;');  
    hideSuggest(w);
  }
}

function _doLoadSuggest(fn,w,prefix,s) {
  var req = new JsHttpRequest();
  req.onreadystatechange = function() {
      if (req.readyState == 4) {
          if (req.responseJS) {
            _addArSuggest(w);
            obj=document.all?document.all['sugg_'+w]:document.getElementById('sugg_'+w);
            if (obj) {obj.innerHTML = req.responseJS.html;}
            _fl_sugg_run=false;
            onSuggSetActive(prefix,1);
          }
      }
  }
  s=escape(s);
  req.caching=true; req.open('POST',('http://'+location.hostname+'/?jsload='+w+'&sbeg='+s+'&fname='+fn+'&prefix='+prefix+'&'),true); req.send();
}

function doSuggest(fn,finp,prefix,fsadd) {
//  if (!_fl_sugg_open) {
//  if (!_fl_sugg_run) {
  _fl_sugg_add=fsadd;
  _fl_sugg_run=true;
   eval('s=document.'+fn+'.'+finp+'.value;');  
  _now = new Date();
  _ms=_now.getTime(); 
	 s=escape(s);
	 ids=finp+s+fn+prefix;
	 idcache='';
	 for (i=0; i<ids.length; i++) {
	   idcache+=ids.charCodeAt(i);
	 }
	 if (_isugg_cache[idcache]) {
	    $('#sugg_'+finp).html(_isugg_cache[idcache]); 
	 } else {
		 $.post('?',{jajax:finp,_s_sbeg:s,fname:fn,prefix:prefix,_st_idcache:idcache},function(xml) {
				 _addArSuggest($("jajax",xml).text());
				 $('#sugg_'+$("jajax",xml).text()).html($("html",xml).text()); 
				 _fl_sugg_run=false;
				 onSuggSetActive($("prefix",xml).text(),1);
				 _isugg_cache[$("idcache",xml).text()]=$("html",xml).text();
		 });
	 }
//  } else {
//if (obj) {obj.innerHTML = (_ms-_ms_sugg_prev)+" : "+_tid+" : "+"_doLoadSuggest('"+fn+"','"+finp+"','"+prefix+"',"+s+");";}    
//    window.clearTimeout(_tid);
//    _tid=window.setTimeout("_doLoadSuggest('"+fn+"','"+finp+"','"+prefix+"','"+s+"');",(_ms-_ms_sugg_prev));
//  }
  _ms_sugg_prev=_ms;
//  }
//  }
}

function hideSuggest(w) {
  obj=document.all?document.all['sugg_'+w]:document.getElementById('sugg_'+w);  if (obj) {obj.innerHTML = '';}
  _fl_sugg_open=false;
}

function onSuggSetActive(prefix, i) {
  obji=document.all?document.all[prefix+'_isugg_'+i]:document.getElementById(prefix+'_isugg_'+i);
  objo=document.all?document.all[prefix+'_isugg_'+_isugg]:document.getElementById(prefix+'_isugg_'+_isugg);
//  if (obji && (objo || _isugg==-1)) {
  if (obji) {
    if (objo) {objo.className='sugg';}
    obji.className='sugg_hover';
    _isugg=i;
  }
  _fl_sugg_open=true;
//window.status=window.status+'true';  
}

function onSuggKeyUpDown(fname, finp, prefix, fsadd, e) {
  var kk = navigator.appName == 'Netscape' ? e.which : e.keyCode;
window.status=window.status+'UP:'+kk+_fl_sugg_open;  
//  alert(_fl_sugg_open);
  if (kk==13) {_fl13=true;} else {_fl13=false;}
  if (kk==13 && _fl_sugg_open) {setSuggestToInput(fname,finp,prefix,_isugg); return true;}
  if (kk==38 && _fl_sugg_open) {onSuggSetActive(prefix,(_isugg-1)); return false;}
  if (kk==40 && _fl_sugg_open) {onSuggSetActive(prefix,(_isugg+1)); return false;}
  if (kk==27 && _fl_sugg_open) {hideSuggest(finp); return false;}
  doSuggest(fname,finp,prefix,fsadd);
  return false;
}

function onSuggKeyDown13() {
  var kk = navigator.appName == 'Netscape' ? e.which : e.keyCode;
  if (kk==13) {_fl_sugg_open=true;}
window.status=window.status+'DONW:'+kk+_fl_sugg_open;    
}

function onMouseSuggOut() {_fl_sugg_mo=false;}

function onMouseSuggSetActive(prefix, i) {
  if (!_fl_sugg_mo) {onSuggSetActive(prefix, i);}
  _fl_sugg_mo=true;
}

function _hideSuggestAll() {for (i=0; i<_ar_sugg.length; i++) {hideSuggest(_ar_sugg[i]);}}
