/*
 * jQuery JavaScript Library v1.3.2
 * http://jquery.com/
 *
 * Copyright (c) 2009 John Resig
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
 * Revision: 6246
 */
(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});
/*
 * Sizzle CSS Selector Engine - v0.9.3
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML='   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})();
/*
 * jQuery blockUI plugin
 * Version 2.14 (18-JAN-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;
}

// global $ methods for blocking/unblocking the entire page
$.blockUI   = function(opts, type) { install(window, opts, type); };
$.unblockUI = function(opts, type) { remove(window, opts, type); };

// 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.14; // 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',
        //cursor:         'default',
        backgroundColor:'#fff'
    },
    
    // 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:   'default',
	    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,
    
    /* gch added */
    busyCursor: 'normal'
    /* gch added */
};

// private data and functions follow...

var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent);
var pageBlock = null;
var pageBlockEls = [];

function install(el, opts, type) {
    
    
	type = type !== undefined ? type : 0;
	if (type != 0){
		if(typeof($("#spMess"))!=="undefined")
			if((typeof($("#spMess").attr('id_sp'))!=="undefined") && (typeof($("#spMess").attr('status'))!=="undefined"))
				if($("#spMess").attr('id_sp') == type)
					if($("#spMess").attr('status') == 1)
						return 0;
	}	
    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
    
    if(type == 0){
	    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="javascript:false;"></iframe>')
	                                : $('<div class="blockUI" style="display:none"></div>');
	    var lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ z++ +';display:none;cursor:'+opts.busyCursor+';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>');
    }else{
	    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="javascript:false;"></iframe>')
                : $('<div class="blockUI" style="display:none"></div>');
		var lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ z++ +';display:none;cursor:'+opts.busyCursor+';border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
		var lyr3 = full ? $('<div id="spMess" id_sp="' + type + '" status="1" class="blockUI blockMsg blockPage" style="z-index:'+z+';display:none;position:fixed"></div>')
		    : $('<div id="spMess" id_sp="' + type + '" status="1" 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);
     
//     window_debug( css, 'css' );
//     window_debug( $.blockUI.defaults.css, 'blockUI' );
//     window_debug( opts.css, 'opts' );    
//     window_debug( $.blockUI.defaults, 'blockUI_def' );    
     

    // 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 && (!$.boxModel || $('object,embed', full ? null : el).length > 0);
    if (ie6 || expr) {
        // 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
    lyr3.append(msg);//.show();
    if (msg && (msg.jquery || msg.nodeType))
        $(msg).show();

	if (opts.fadeIn) {
		if ($.browser.msie && opts.showOverlay)
			lyr1.fadeIn(opts.fadeIn);
		if (opts.showOverlay)
			lyr2.fadeIn(opts.fadeIn);
		lyr3.fadeIn(opts.fadeIn);
	}
	else {
		if ($.browser.msie && opts.showOverlay)
			lyr1.show();
		if (opts.showOverlay)
			lyr2.show();
		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
		if(type == 0){
			setTimeout(function() {
				full ? $.unblockUI(opts) : $(el).unblock(opts);
			}, opts.timeout);
		}else{
			setTimeout(function() {
				var base_type = type;
				if((typeof($("#spMess").attr('id_sp'))!=="undefined") && (typeof($("#spMess").attr('status'))!=="undefined")) {
					var curr_type = $("#spMess").attr('id_sp');
					var curr_status = $("#spMess").attr('status');
					//alert("base_type:"+base_type+"; curr_type:"+curr_type);
					if((curr_type == base_type) && (curr_status == 1)){
						$("#spMess").attr('status', '0');
						full ? $.unblockUI(opts, base_type) : $(el).unblock(opts, base_type);
					}
				}
			}, opts.timeout);
		}
	}
};

// remove the block
function remove(el, opts, type) {
	type = type !== undefined ? type : 0;
    var full = el == window;
    var data = $(el).data('blockUI.history');
    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);
        if(type == 0){
        	setTimeout(function() {reset(els,data,opts,el);}, opts.fadeOut);
        }else{
	        setTimeout(function() {
	          var base_type = type;
			  if((typeof($("#spMess").attr('id_sp'))!=="undefined") && (typeof($("#spMess").attr('status'))!=="undefined")) {
				var curr_type = $("#spMess").attr('id_sp');
				var curr_status = $("#spMess").attr('status');
				//alert("base_type:"+base_type+"; curr_type:"+curr_type);
				if((curr_type == base_type) && (curr_status == 0)){
					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);

/**
 * JsHttpRequest: JavaScript "AJAX" data loader
 *
 * @license LGPL
 * @author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/
 * @version 5.x $Id$
 */

// {{{
function JsHttpRequest() {
    // Standard properties.
    var t = this;
    t.onreadystatechange = null;
    t.readyState         = 0;
    t.responseText       = null;
    t.responseXML        = null;
    t.status             = 200;
    t.statusText         = "OK";
    // JavaScript response array/hash
    t.responseJS         = null;

    // Additional properties.
    t.caching            = false;        // need to use caching?
    t.loader             = null;         // loader to use ('form', 'script', 'xml'; null - autodetect)
    t.session_name       = "PHPSESSID";  // set to SID cookie or GET parameter name

    // Internals.
    t._ldObj              = null;  // used loader object
    t._reqHeaders        = [];    // collected request headers
    t._openArgs          = null;  // parameters from open()
    t._errors = {
        inv_form_el:        'Invalid FORM element detected: name=%, tag=%',
        must_be_single_el:  'If used, <form> must be a single HTML element in the list.',
        js_invalid:         'JavaScript code generated by backend is invalid!\n%',
        url_too_long:       'Cannot use so long query with GET request (URL is larger than % bytes)',
        unk_loader:         'Unknown loader: %',
        no_loaders:         'No loaders registered at all, please check JsHttpRequest.LOADERS array',
        no_loader_matched:  'Cannot find a loader which may process the request. Notices are:\n%'
    }
    
    /**
     * Aborts the request. Behaviour of this function for onreadystatechange() 
     * is identical to IE (most universal and common case). E.g., readyState -> 4
     * on abort() after send().
     */
    t.abort = function() { with (this) {
        if (_ldObj && _ldObj.abort) _ldObj.abort();
        _cleanup();
        if (readyState == 0) {
            // start->abort: no change of readyState (IE behaviour)
            return;
        }
        if (readyState == 1 && !_ldObj) {
            // open->abort: no onreadystatechange call, but change readyState to 0 (IE).
            // send->abort: change state to 4 (_ldObj is not null when send() is called)
            readyState = 0;
            return;
        }
        _changeReadyState(4, true); // 4 in IE & FF on abort() call; Opera does not change to 4.
    }}
    
    /**
     * Prepares the object for data loading.
     * You may also pass URLs like "GET url" or "script.GET url".
     */
    t.open = function(method, url, asyncFlag, username, password) { with (this) {
        // Extract methor and loader from the URL (if present).
        if (url.match(/^((\w+)\.)?(GET|POST)\s+(.*)/i)) {
            this.loader = RegExp.$2? RegExp.$2 : null;
            method = RegExp.$3;
            url = RegExp.$4; 
        }
        // Append SID to original URL. Use try...catch for security problems.
        try {
            if (
                document.location.search.match(new RegExp('[&?]' + session_name + '=([^&?]*)'))
                || document.cookie.match(new RegExp('(?:;|^)\\s*' + session_name + '=([^;]*)'))
            ) {
                url += (url.indexOf('?') >= 0? '&' : '?') + session_name + "=" + this.escape(RegExp.$1);
            }
        } catch (e) {}
        // Store open arguments to hash.
        _openArgs = {
            method:     (method || '').toUpperCase(),
            url:        url,
            asyncFlag:  asyncFlag,
            username:   username != null? username : '',
            password:   password != null? password : ''
        }
        _ldObj = null;
        _changeReadyState(1, true); // compatibility with XMLHttpRequest
        return true;
    }}
    
    /**
     * Sends a request to a server.
     */
    t.send = function(content) {
        if (!this.readyState) {
            // send without open or after abort: no action (IE behaviour).
            return;
        }
        this._changeReadyState(1, true); // compatibility with XMLHttpRequest
        this._ldObj = null;
        
        // Prepare to build QUERY_STRING from query hash.
        var queryText = [];
        var queryElem = [];
        if (!this._hash2query(content, null, queryText, queryElem)) return;
    
        // Solve the query hashcode & return on cache hit.
        var hash = null;
        if (this.caching && !queryElem.length) {
            hash = this._openArgs.username + ':' + this._openArgs.password + '@' + this._openArgs.url + '|' + queryText + "#" + this._openArgs.method;
            var cache = JsHttpRequest.CACHE[hash];
            if (cache) {
                this._dataReady(cache[0], cache[1]);
                return false;
            }
        }
    
        // Try all the loaders.
        var loader = (this.loader || '').toLowerCase();
        if (loader && !JsHttpRequest.LOADERS[loader]) return this._error('unk_loader', loader);
        var errors = [];
        var lds = JsHttpRequest.LOADERS;
        for (var tryLoader in lds) {
            var ldr = lds[tryLoader].loader;
            if (!ldr) continue; // exclude possibly derived prototype properties from "for .. in".
            if (loader && tryLoader != loader) continue;
            // Create sending context.
            var ldObj = new ldr(this);
            JsHttpRequest.extend(ldObj, this._openArgs);
            JsHttpRequest.extend(ldObj, {
                queryText:  queryText.join('&'),
                queryElem:  queryElem,
                id:         (new Date().getTime()) + "" + JsHttpRequest.COUNT++,
                hash:       hash,
                span:       null
            });
            var error = ldObj.load();
            if (!error) {
                // Save loading script.
                this._ldObj = ldObj;
                JsHttpRequest.PENDING[ldObj.id] = this;
                return true;
            }
            if (!loader) {
                errors[errors.length] = '- ' + tryLoader.toUpperCase() + ': ' + this._l(error);
            } else {
                return this._error(error);
            }
        }
    
        // If no loader matched, generate error message.
        return tryLoader? this._error('no_loader_matched', errors.join('\n')) : this._error('no_loaders');
    }
    
    /**
     * Returns all response headers (if supported).
     */
    t.getAllResponseHeaders = function() { with (this) {
        return _ldObj && _ldObj.getAllResponseHeaders? _ldObj.getAllResponseHeaders() : [];
    }}

    /**
     * Returns one response header (if supported).
     */
    t.getResponseHeader = function(label) { with (this) {
        return _ldObj && _ldObj.getResponseHeader? _ldObj.getResponseHeader(label) : null;
    }}

    /**
     * Adds a request header to a future query.
     */
    t.setRequestHeader = function(label, value) { with (this) {
        _reqHeaders[_reqHeaders.length] = [label, value];
    }}
    
    //
    // Internal functions.
    //
    
    /**
     * Do all the work when a data is ready.
     */
    t._dataReady = function(text, js) { with (this) {
        if (caching && _ldObj) JsHttpRequest.CACHE[_ldObj.hash] = [text, js];
        responseText = responseXML = text;
        responseJS = js;
        if (js !== null) {
            status = 200;
            statusText = "OK";
        } else {
            // The special value "null" from a backend means Fatal error.
            // User cannot assign null to $_RESULT manually, it is 
            // translated to false to avoid 500 error collisions.
            status = 500;
            statusText = "Internal Server Error";
        }
        _changeReadyState(2);
        _changeReadyState(3);
        _changeReadyState(4);
        _cleanup();
    }}
    
    /**
     * Analog of sprintf(), but translates the first parameter by _errors.
     */
    t._l = function(args) {
        var i = 0, p = 0, msg = this._errors[args[0]];
        // Cannot use replace() with a callback, because it is incompatible with IE5.
        while ((p = msg.indexOf('%', p)) >= 0) {
            var a = args[++i] + "";
            msg = msg.substring(0, p) + a + msg.substring(p + 1, msg.length);
            p += 1 + a.length;
        }
        return msg;
    }

    /** 
     * Called on error.
     */
    t._error = function(msg) {
        msg = this._l(typeof(msg) == 'string'? arguments : msg)
        msg = "JsHttpRequest: " + msg;
        if (!window.Error) {
            // Very old browser...
            throw msg;
        } else if ((new Error(1, 'test')).description == "test") {
            // We MUST (!!!) pass 2 parameters to the Error() constructor for IE5.
            throw new Error(1, msg);
        } else {
            // Mozilla does not support two-parameter call style.
            throw new Error(msg);
        }
    }
    
    /**
     * Convert hash to QUERY_STRING.
     * If next value is scalar or hash, push it to queryText.
     * If next value is form element, push [name, element] to queryElem.
     */
    t._hash2query = function(content, prefix, queryText, queryElem) {
        if (prefix == null) prefix = "";
        if((''+typeof(content)).toLowerCase() == 'object') {
            var formAdded = false;
            if (content && content.parentNode && content.parentNode.appendChild && content.tagName && content.tagName.toUpperCase() == 'FORM') {
                content = { form: content };
            }
            for (var k in content) {
                var v = content[k];
                if (v instanceof Function) continue;
                var curPrefix = prefix? prefix + '[' + this.escape(k) + ']' : this.escape(k);
                var isFormElement = v && v.parentNode && v.parentNode.appendChild && v.tagName;
                if (isFormElement) {
                    var tn = v.tagName.toUpperCase();
                    if (tn == 'FORM') {
                        // FORM itself is passed.
                        formAdded = true;
                    } else if (tn == 'INPUT' || tn == 'TEXTAREA' || tn == 'SELECT') {
                        // This is a single form elemenent.
                    } else {
                        return this._error('inv_form_el', (v.name||''), v.tagName);
                    }
                    queryElem[queryElem.length] = { name: curPrefix, e: v };
                } else if (v instanceof Object) {
                    this._hash2query(v, curPrefix, queryText, queryElem);
                } else {
                    // We MUST skip NULL values, because there is no method
                    // to pass NULL's via GET or POST request in PHP.
                    if (v === null) continue;
                    // Convert JS boolean true and false to corresponding PHP values.
                    if (v === true) v = 1; 
                    if (v === false) v = '';
                    queryText[queryText.length] = curPrefix + "=" + this.escape('' + v);
                }
                if (formAdded && queryElem.length > 1) {
                    return this._error('must_be_single_el');
                }
            }
        } else {
            queryText[queryText.length] = content;
        }
        return true;
    }
    
    /**
     * Remove last used script element (clean memory).
     */
    t._cleanup = function() {
        var ldObj = this._ldObj;
        if (!ldObj) return;
        // Mark this loading as aborted.
        JsHttpRequest.PENDING[ldObj.id] = false;
        var span = ldObj.span;
        if (!span) return;
        // Do NOT use iframe.contentWindow.back() - it is incompatible with Opera 9!
        ldObj.span = null;
        var closure = function() {
            span.parentNode.removeChild(span);
        }
        // IE5 crashes on setTimeout(function() {...}, ...) construction! Use tmp variable.
        JsHttpRequest.setTimeout(closure, 50);
    }
    
    /**
     * Change current readyState and call trigger method.
     */
    t._changeReadyState = function(s, reset) { with (this) {
        if (reset) {
            status = statusText = responseJS = null;
            responseText = '';
        }
        readyState = s;
        if (onreadystatechange) onreadystatechange();
    }}
    
    /**
     * JS escape() does not quote '+'.
     */
    t.escape = function(s) {
        return escape(s).replace(new RegExp('\\+','g'), '%2B');
    }
}


// Global library variables.
JsHttpRequest.COUNT = 0;              // unique ID; used while loading IDs generation
JsHttpRequest.MAX_URL_LEN = 2000;     // maximum URL length
JsHttpRequest.CACHE = {};             // cached data
JsHttpRequest.PENDING = {};           // pending loadings
JsHttpRequest.LOADERS = {};           // list of supported data loaders (filled at the bottom of the file)
JsHttpRequest._dummy = function() {}; // avoid memory leaks


/**
 * These functions are dirty hacks for IE 5.0 which does not increment a
 * reference counter for an object passed via setTimeout(). So, if this 
 * object (closure function) is out of scope at the moment of timeout 
 * applying, IE 5.0 crashes. 
 */

/**
 * Timeout wrappers storage. Used to avoid zeroing of referece counts in IE 5.0.
 * Please note that you MUST write "window.setTimeout", not "setTimeout", else
 * IE 5.0 crashes again. Strange, very strange...
 */
JsHttpRequest.TIMEOUTS = { s: window.setTimeout, c: window.clearTimeout };

/**
 * Wrapper for IE5 buggy setTimeout.
 * Use this function instead of a usual setTimeout().
 */
JsHttpRequest.setTimeout = function(func, dt) {
    // Always save inside the window object before a call (for FF)!
    window.JsHttpRequest_tmp = JsHttpRequest.TIMEOUTS.s; 
    if (typeof(func) == "string") {
        id = window.JsHttpRequest_tmp(func, dt);
    } else {
        var id = null;
        var mediator = function() {
            func();
            delete JsHttpRequest.TIMEOUTS[id]; // remove circular reference
        }
        id = window.JsHttpRequest_tmp(mediator, dt);
        // Store a reference to the mediator function to the global array
        // (reference count >= 1); use timeout ID as an array key;
        JsHttpRequest.TIMEOUTS[id] = mediator;
    }
    window.JsHttpRequest_tmp = null; // no delete() in IE5 for window
    return id;
}

/**
 * Complimental wrapper for clearTimeout. 
 * Use this function instead of usual clearTimeout().
 */
JsHttpRequest.clearTimeout = function(id) {
    window.JsHttpRequest_tmp = JsHttpRequest.TIMEOUTS.c;
    delete JsHttpRequest.TIMEOUTS[id]; // remove circular reference
    var r = window.JsHttpRequest_tmp(id);
    window.JsHttpRequest_tmp = null; // no delete() in IE5 for window
    return r;
}


/**
 * Global static function.
 * Simple interface for most popular use-cases.
 * You may also pass URLs like "GET url" or "script.GET url".
 */
JsHttpRequest.query = function(url, content, onready, nocache) {
    var req = new this();
    
    var browser = navigator.userAgent.toLowerCase();
    //alert(browser);
    var isIE = (browser.indexOf("msie") != -1)
    if (isIE)
    {
        req.loader = 'script';
    }
    req.caching = !nocache;
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            onready(req.responseJS, req.responseText);
        }
    }
    req.open(null, url, true);
    req.send(content);
}


/**
 * Global static function.
 * Called by server backend script on data load.
 */
JsHttpRequest.dataReady = function(d) {
    var th = this.PENDING[d.id];
    delete this.PENDING[d.id];
    if (th) {
        th._dataReady(d.text, d.js);
    } else if (th !== false) {
        throw "dataReady(): unknown pending id: " + d.id;
    }
}


// Adds all the properties of src to dest.
JsHttpRequest.extend = function(dest, src) {
    for (var k in src) dest[k] = src[k];
}

/**
 * Each loader has the following properties which must be initialized:
 * - method
 * - url
 * - asyncFlag (ignored)
 * - username
 * - password
 * - queryText (string)
 * - queryElem (array)
 * - id
 * - hash
 * - span
 */ 
 
// }}}

// {{{ xml
// Loader: XMLHttpRequest or ActiveX.
// [+] GET and POST methods are supported.
// [+] Most native and memory-cheap method.
// [+] Backend data can be browser-cached.
// [-] Cannot work in IE without ActiveX. 
// [-] No support for loading from different domains.
// [-] No uploading support.
//
JsHttpRequest.LOADERS.xml = { loader: function(req) {
    JsHttpRequest.extend(req._errors, {
        xml_no:          'Cannot use XMLHttpRequest or ActiveX loader: not supported',
        xml_no_diffdom:  'Cannot use XMLHttpRequest to load data from different domain %',
        xml_no_headers:  'Cannot use XMLHttpRequest loader or ActiveX loader, POST method: headers setting is not supported, needed to work with encodings correctly',
        xml_no_form_upl: 'Cannot use XMLHttpRequest loader: direct form elements using and uploading are not implemented'
    });
    
    this.load = function() {
        if (this.queryElem.length) return ['xml_no_form_upl'];
        
        // XMLHttpRequest (and MS ActiveX'es) cannot work with different domains.
        if (this.url.match(new RegExp('^([a-z]+://[^\\/]+)(.*)', 'i'))) {
        	// We MUST also check if protocols matched: cannot send from HTTP 
        	// to HTTPS and vice versa.
            if (RegExp.$1.toLowerCase() != document.location.protocol + '//' + document.location.hostname.toLowerCase()) {
                return ['xml_no_diffdom', RegExp.$1];
            }
        }
        
        // Try to obtain a loader.
        var xr = null;
        if (window.XMLHttpRequest) {
            try { xr = new XMLHttpRequest() } catch(e) {}
        } else if (window.ActiveXObject) {
            try { xr = new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
            if (!xr) try { xr = new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {}
        }
        if (!xr) return ['xml_no'];
        
        // Loading method detection. We cannot POST if we cannot set "octet-stream" 
        // header, because we need to process the encoded data in the backend manually.
        var canSetHeaders = window.ActiveXObject || xr.setRequestHeader;
        if (!this.method) this.method = canSetHeaders && this.queryText.length? 'POST' : 'GET';
        
        // Build & validate the full URL.
        if (this.method == 'GET') {
            if (this.queryText) this.url += (this.url.indexOf('?') >= 0? '&' : '?') + this.queryText;
            this.queryText = '';
            if (this.url.length > JsHttpRequest.MAX_URL_LEN) return ['url_too_long', JsHttpRequest.MAX_URL_LEN];
        } else if (this.method == 'POST' && !canSetHeaders) {
            return ['xml_no_headers'];
        }
        
        // Add ID to the url if we need to disable the cache.
        this.url += (this.url.indexOf('?') >= 0? '&' : '?') + 'JsHttpRequest=' + (req.caching? '0' : this.id) + '-xml';        
        
        // Assign the result handler.
        var id = this.id;
        xr.onreadystatechange = function() { 
 //       		alert('rs:'+xr.readyState+'\nstatus:'+xr.status);
        		
        	  // MB <---
        		if (typeof(xr.readyState) == 'undefined')
        			return;
         	  // MB --->
        		
            if (xr.readyState != 4) {
            	// MB <---
            	try { 
	                // In case of abort() call, xr.status is unavailable and generates exception.
	                // But xr.readyState equals to 4 in this case. Stupid behaviour. :-(
	                req.status = xr.status;
	                req.responseText = xr.responseText;
	                req._changeReadyState(xr.readyState);
	            } catch (e) {req._changeReadyState(xr.readyState);}	            
	            // MB --->
            	return;
            }
            // Avoid memory leak by removing the closure.
            xr.onreadystatechange = JsHttpRequest._dummy;
            req.status = null;
            try { 
                // In case of abort() call, xr.status is unavailable and generates exception.
                // But xr.readyState equals to 4 in this case. Stupid behaviour. :-(
                req.status = xr.status;
                req.responseText = xr.responseText;
            } catch (e) {}
            if (!req.status) {
            	// MB <---
            	req._changeReadyState(xr.readyState);
            	// MB --->
            	return;
            }
            try {
                // Damned Opera returned empty responseText when Status is not 200.
                var rtext = req.responseText || '{ js: null, text: null }';
                // Prepare generator function & catch syntax errors on this stage.
                eval('JsHttpRequest._tmp = function(id) { var d = ' + rtext + '; d.id = id; JsHttpRequest.dataReady(d); }');
            } catch (e) {
                // Note that FF 2.0 does not throw any error from onreadystatechange handler.
            		// MB <---
            		req._changeReadyState(xr.readyState);
            		// MB --->
                return req._error('js_invalid', req.responseText)
            }
            // Call associated dataReady() outside the try-catch block 
            // to pass exceptions in onreadystatechange in usual manner.
            JsHttpRequest._tmp(id);
            JsHttpRequest._tmp = null;
        };

        // Open & send the request.
        xr.open(this.method, this.url, true, this.username, this.password);
        if (canSetHeaders) {
            // Pass pending headers.
            for (var i = 0; i < req._reqHeaders.length; i++) {
                xr.setRequestHeader(req._reqHeaders[i][0], req._reqHeaders[i][1]);
            }
            // Set non-default Content-type. We cannot use 
            // "application/x-www-form-urlencoded" here, because 
            // in PHP variable HTTP_RAW_POST_DATA is accessible only when 
            // enctype is not default (e.g., "application/octet-stream" 
            // is a good start). We parse POST data manually in backend 
            // library code. Note that Safari sets by default "x-www-form-urlencoded"
            // header, but FF sets "text/xml" by default.
            xr.setRequestHeader('Content-Type', 'application/octet-stream');
        }
        xr.send(this.queryText);
        
        // No SPAN is used for this loader.
        this.span = null;
        this.xr = xr; // save for later usage on abort()
        
        // Success.
        return null;
    }
    
    // Override req.getAllResponseHeaders method.
    this.getAllResponseHeaders = function() {
        return this.xr.getAllResponseHeaders();
    }
    
    // Override req.getResponseHeader method.
    this.getResponseHeader = function(label) {
        return this.xr.getResponseHeader(label);
    }

    this.abort = function() {
        this.xr.abort();
        this.xr = null;
    }
}}
// }}}


// {{{ script
// Loader: SCRIPT tag.
// [+] Most cross-browser. 
// [+] Supports loading from different domains.
// [-] Only GET method is supported.
// [-] No uploading support.
// [-] Backend data cannot be browser-cached.
//
JsHttpRequest.LOADERS.script = { loader: function(req) {
    JsHttpRequest.extend(req._errors, {
        script_only_get:   'Cannot use SCRIPT loader: it supports only GET method',
        script_no_form:    'Cannot use SCRIPT loader: direct form elements using and uploading are not implemented'
    })
    
    this.load = function() {
        // Move GET parameters to the URL itself.
        if (this.queryText) this.url += (this.url.indexOf('?') >= 0? '&' : '?') + this.queryText;
        this.url += (this.url.indexOf('?') >= 0? '&' : '?') + 'JsHttpRequest=' + this.id + '-' + 'script';        
        this.queryText = '';
        
        if (!this.method) this.method = 'GET';
        if (this.method !== 'GET') return ['script_only_get'];
        if (this.queryElem.length) return ['script_no_form'];
        if (this.url.length > JsHttpRequest.MAX_URL_LEN) return ['url_too_long', JsHttpRequest.MAX_URL_LEN];

        var th = this, d = document, s = null, b = d.body;
        if (!window.opera) {
            // Safari, IE, FF, Opera 7.20.
            this.span = s = d.createElement('SCRIPT');
            var closure = function() {
                s.language = 'JavaScript';
                if (s.setAttribute) s.setAttribute('src', th.url); else s.src = th.url;
                b.insertBefore(s, b.lastChild);
            }
        } else {
            // Oh shit! Damned stupid Opera 7.23 does not allow to create SCRIPT 
            // element over createElement (in HEAD or BODY section or in nested SPAN - 
            // no matter): it is created deadly, and does not response the href assignment.
            // So - always create SPAN.
            this.span = s = d.createElement('SPAN');
            s.style.display = 'none';
            b.insertBefore(s, b.lastChild);
            s.innerHTML = 'Workaround for IE.<s'+'cript></' + 'script>';
            var closure = function() {
                s = s.getElementsByTagName('SCRIPT')[0]; // get with timeout!
                s.language = 'JavaScript';
                if (s.setAttribute) s.setAttribute('src', th.url); else s.src = th.url;
            }
        }
        JsHttpRequest.setTimeout(closure, 10);
        
        // Success.
        return null;
    }
}}
// }}}


// {{{ form
// Loader: FORM & IFRAME.
// [+] Supports file uploading.
// [+] GET and POST methods are supported.
// [+] Supports loading from different domains.
// [-] Uses a lot of system resources.
// [-] Backend data cannot be browser-cached.
// [-] Pollutes browser history on some old browsers.
//
JsHttpRequest.LOADERS.form = { loader: function(req) {
    JsHttpRequest.extend(req._errors, {
        form_el_not_belong:  'Element "%" does not belong to any form!',
        form_el_belong_diff: 'Element "%" belongs to a different form. All elements must belong to the same form!',
        form_el_inv_enctype: 'Attribute "enctype" of the form must be "%" (for IE), "%" given.'
    })
    
    this.load = function() {
        var th = this;
     
        if (!th.method) th.method = 'POST';
        th.url += (th.url.indexOf('?') >= 0? '&' : '?') + 'JsHttpRequest=' + th.id + '-' + 'form';
        
        // If GET, build full URL. Then copy QUERY_STRING to queryText.
        if (th.method == 'GET') {
            if (th.queryText) th.url += (th.url.indexOf('?') >= 0? '&' : '?') + th.queryText;
            if (th.url.length > JsHttpRequest.MAX_URL_LEN) return ['url_too_long', JsHttpRequest.MAX_URL_LEN];
            var p = th.url.split('?', 2);
            th.url = p[0];
            th.queryText = p[1] || '';
        }

        // Check if all form elements belong to same form.
        var form = null;
        var wholeFormSending = false;
        if (th.queryElem.length) {
            if (th.queryElem[0].e.tagName.toUpperCase() == 'FORM') {
                // Whole FORM sending.
                form = th.queryElem[0].e;
                wholeFormSending = true;
                th.queryElem = [];
            } else {
                // If we have at least one form element, we use its FORM as a POST container.
                form = th.queryElem[0].e.form;
                // Validate all the elements.
                for (var i = 0; i < th.queryElem.length; i++) {
                    var e = th.queryElem[i].e;
                    if (!e.form) {
                        return ['form_el_not_belong', e.name];
                    }
                    if (e.form != form) {
                        return ['form_el_belong_diff', e.name];
                    }
                }
            }
            
            // Check enctype of the form.
            if (th.method == 'POST') {
                var need = "multipart/form-data";
                var given = (form.attributes.encType && form.attributes.encType.nodeValue) || (form.attributes.enctype && form.attributes.enctype.value) || form.enctype;
                if (given != need) {
                    return ['form_el_inv_enctype', need, given];
                }
            }
        }

        // Create invisible IFRAME with temporary form (form is used on empty queryElem).
        // We ALWAYS create th IFRAME in the document of the form - for Opera 7.20.
        var d = form && (form.ownerDocument || form.document) || document;
        var ifname = 'jshr_i_' + th.id;
        var s = th.span = d.createElement('DIV');
        s.style.position = 'absolute';
        s.style.display = 'none';
        s.style.visibility = 'hidden';
        s.innerHTML = 
            (form? '' : '<form' + (th.method == 'POST'? ' enctype="multipart/form-data" method="post"' : '') + '></form>') + // stupid IE, MUST use innerHTML assignment :-(
            '<iframe name="' + ifname + '" id="' + ifname + '" style="width:0px; height:0px; overflow:hidden; border:none"></iframe>'
        if (!form) {
            form = th.span.firstChild;
        }

        // Insert generated form inside the document.
        // Be careful: don't forget to close FORM container in document body!
        d.body.insertBefore(s, d.body.lastChild);

        // Function to safely set the form attributes. Parameter attr is NOT a hash 
        // but an array, because "for ... in" may badly iterate over derived attributes.
        var setAttributes = function(e, attr) {
            var sv = [];
            var form = e;
            // This strange algorythm is needed, because form may  contain element 
            // with name like 'action'. In IE for such attribute will be returned
            // form element node, not form action. Workaround: copy all attributes
            // to new empty form and work with it, then copy them back. This is
            // THE ONLY working algorythm since a lot of bugs in IE5.0 (e.g. 
            // with e.attributes property: causes IE crash).
            if (e.mergeAttributes) {
                var form = d.createElement('form');
                form.mergeAttributes(e, false);
            }
            for (var i = 0; i < attr.length; i++) {
                var k = attr[i][0], v = attr[i][1];
                // TODO: http://forum.dklab.ru/viewtopic.php?p=129059#129059
                sv[sv.length] = [k, form.getAttribute(k)];
                form.setAttribute(k, v);
            }
            if (e.mergeAttributes) {
                e.mergeAttributes(form, false);
            }
            return sv;
        }

        // Run submit with delay - for old Opera: it needs some time to create IFRAME.
        var closure = function() {
            // Save JsHttpRequest object to new IFRAME.
            top.JsHttpRequestGlobal = JsHttpRequest;
            
            // Disable ALL the form elements.
            var savedNames = [];
            if (!wholeFormSending) {
                for (var i = 0, n = form.elements.length; i < n; i++) {
                    savedNames[i] = form.elements[i].name;
                    form.elements[i].name = '';
                }
            }

            // Insert hidden fields to the form.
            var qt = th.queryText.split('&');
            for (var i = qt.length - 1; i >= 0; i--) {
                var pair = qt[i].split('=', 2);
                var e = d.createElement('INPUT');
                e.type = 'hidden';
                e.name = unescape(pair[0]);
                e.value = pair[1] != null? unescape(pair[1]) : '';
                form.appendChild(e);
            }


            // Change names of along user-passed form elements.
            for (var i = 0; i < th.queryElem.length; i++) {
                th.queryElem[i].e.name = th.queryElem[i].name;
            }

            // Temporary modify form attributes, submit form, restore attributes back.
            var sv = setAttributes(
                form, 
                [
                    ['action',   th.url],
                    ['method',   th.method],
                    ['onsubmit', null],
                    ['target',   ifname]
                ]
            );
            form.submit();
            setAttributes(form, sv);

            // Remove generated temporary hidden elements from the top of the form.
            for (var i = 0; i < qt.length; i++) {
                // Use "form.firstChild.parentNode", not "form", or IE5 crashes!
                form.lastChild.parentNode.removeChild(form.lastChild);
            }
            // Enable all disabled elements back.
            if (!wholeFormSending) {
                for (var i = 0, n = form.elements.length; i < n; i++) {
                    form.elements[i].name = savedNames[i];
                }
            }
        }
        JsHttpRequest.setTimeout(closure, 100);

        // Success.
        return null;
    }    
}}
// }}}


if (typeof (localizator) != 'function')
{
	
	localizator = function()
	{
		this.arr = {};
		this.add = function (module, add_arr)
		{	
			if (typeof (add_arr) != 'object') return;
			
			for (var block in add_arr)
			{
				if ( typeof (add_arr[block]) == 'object')
				{
					for (var id in add_arr[block])
					{ 
						if (typeof (add_arr[block][id]) == 'string')
						{ 
							
							if (typeof(this.arr[module]) == 'undefined')
							{
								this.arr[module] = {};
							}
							if (typeof(this.arr[module][block]) == 'undefined')
							{
								//alert(' id=' + id + ';  block=' + block + '; res=' + add_arr[block][id] );
								this.arr[module][block] = {};
							}
							if ((typeof(this.arr[module][block][id]) == 'undefined'))
							{
								//alert(' id=' + id + ';  block=' + block + '; res=' + add_arr[block][id] );
								this.arr[module][block][id] = add_arr[block][id];
							}
						}	
					}
				}
				
				
				else if ( typeof (add_arr[block]) == 'string')
				{
					if (typeof(this.arr[module]) == 'undefined')
					{
						//alert(module)
						this.arr[module] = {};
					}
					if (typeof(this.arr[module][block]) == 'undefined')
					{
						this.arr[module][block] = add_arr[block];
					}
				}
			}
		}
		
		this.get = function(module, block, id)
		{
			if (typeof(this.arr[module]) == 'undefined') return null;
			
			if (typeof (block) == 'undefined')
			{
				return this.arr[module];
			}
			
			if (typeof(id) == 'undefined')
			{
				return this.arr[module][block];
			}
			else 
			{
				if (typeof(this.arr[module][block]) == 'undefined') return "";
				
				if (typeof(this.arr[module][block][id] == 'string')) 
					return this.arr[module][block][id]; 
				else return "";
			}
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	var WClocale = new localizator();
}
WClocale.add('main', {"phone_format":{"title":"      :"},"date_format":{"title":"     :"},"time_format":{"title":"     :"},"phone_fit":"Fit","phone_fit2":"Fit2","wrong_number":"  ","wait_call":" ","button_errs":{"title":"     :","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      "},"within2min":" 2 .","not_saved":"!   .","save_contact":" ","check_input":"! -  ,   ","save_click":" -","att_title":"!","tariff":{"title":"     :","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      ","region":": ","cost":", : ","per_min":"\/","per_min50":" &mdash;     50 ","currency":"."},"calendar":"","radio_station":" ,    ","check_num":"      6 ","loading":" ...","waiting":"  ...","auth_block":{"title":"","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      ","region":": ","cost":", : ","per_min":"\/","per_min50":" &mdash;     50 ","currency":".","cancel":"","login":":","passwd":":","enter":"","register":"","forget":" ?"},"auth_errs":{"title":"","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      ","region":": ","cost":", : ","per_min":"\/","per_min50":" &mdash;     50 ","currency":".","cancel":"","login":":","passwd":":","enter":"","register":"","forget":" ?","no_auth":" \/","not":"  "},"click_err":{"title":"","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      ","region":": ","cost":", : ","per_min":"\/","per_min50":" &mdash;     50 ","currency":".","cancel":"","login":":","passwd":":","enter":"","register":"","forget":" ?","no_auth":" \/","not":"  ","undef":" ","request":"  ","request2":"  ."},"continue":"  ","change_state":{"title":"  ","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      ","region":": ","cost":", : ","per_min":"\/","per_min50":" &mdash;     50 ","currency":".","cancel":"","login":":","passwd":":","enter":"","register":"","forget":" ?","no_auth":" \/","not":"  ","undef":" ","request":"  ","request2":"  .","on_off":".\/.  -"},"phone_list":{"title":"  ","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      ","region":": ","cost":", : ","per_min":"\/","per_min50":" &mdash;     50 ","currency":".","cancel":"","login":":","passwd":":","enter":"","register":"","forget":" ?","no_auth":" \/","not":"  ","undef":" ","request":"  ","request2":"  .","on_off":".\/.  -","delete_num":" ","select_num":"    ","insert":"","insert_num":"    ","add_from_file":"    ","add2":"  ","clear_phone":"  ","clear_list":" ","phones_count":"  ","show_by":" :","rows_per_page":"  ","pages":":","add_file":"   ","load":"","choose_txt":"      :","choose_txt_note":"      UTF-8","load_no_more":"      ","already_add":"     ","out_ot":"  ","possible":" ","phone_num":" ","please":",   !"},"rows":{"title":"","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      ","region":": ","cost":", : ","per_min":"\/","per_min50":" &mdash;     50 ","currency":".","cancel":"","login":":","passwd":":","enter":"","register":"","forget":" ?","no_auth":" \/","not":"  ","undef":" ","request":"  ","request2":"  .","on_off":".\/.  -","delete_num":" ","select_num":"    ","insert":"","insert_num":"    ","add_from_file":"    ","add2":"  ","clear_phone":"  ","clear_list":" ","phones_count":"  ","show_by":" :","rows_per_page":"  ","pages":":","add_file":"   ","load":"","choose_txt":"      :","choose_txt_note":"      UTF-8","load_no_more":"      ","already_add":"     ","out_ot":"  ","possible":" ","phone_num":" ","please":",   !","from":"","to":""},"check_file":{"title":"","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      ","region":": ","cost":", : ","per_min":"\/","per_min50":" &mdash;     50 ","currency":".","cancel":"","login":":","passwd":":","enter":"","register":"","forget":" ?","no_auth":" \/","not":"  ","undef":" ","request":"  ","request2":"  .","on_off":".\/.  -","delete_num":" ","select_num":"    ","insert":"","insert_num":"    ","add_from_file":"    ","add2":"  ","clear_phone":"  ","clear_list":" ","phones_count":"  ","show_by":" :","rows_per_page":"  ","pages":":","add_file":"   ","load":"","choose_txt":"      :","choose_txt_note":"      UTF-8","load_no_more":"      ","already_add":"     ","out_ot":"  ","possible":" ","phone_num":" ","please":",   !","from":"","to":"","format":"  ","send":"   "},"set_sched":" ","no_mid":"         .    2 :  23:59   00:00.","mode_24_7":"     .    .","days_type":{"title":"","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      ","region":": ","cost":", : ","per_min":"\/","per_min50":" &mdash;     50 ","currency":".","cancel":"","login":":","passwd":":","enter":"","register":"","forget":" ?","no_auth":" \/","not":"  ","undef":" ","request":"  ","request2":"  .","on_off":".\/.  -","delete_num":" ","select_num":"    ","insert":"","insert_num":"    ","add_from_file":"    ","add2":"  ","clear_phone":"  ","clear_list":" ","phones_count":"  ","show_by":" :","rows_per_page":"  ","pages":":","add_file":"   ","load":"","choose_txt":"      :","choose_txt_note":"      UTF-8","load_no_more":"      ","already_add":"     ","out_ot":"  ","possible":" ","phone_num":" ","please":",   !","from":"","to":"","format":"  ","send":"   ","on":" ","off":" ","all":" ","24_7":" "},"change":"","download":"","delete":"","choose":" ->","choose_vmsg":"  ","choose_msg":"  ","attach":" ","close":"","err_text":{"title":"","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      ","region":": ","cost":", : ","per_min":"\/","per_min50":" &mdash;     50 ","currency":".","cancel":"","login":":","passwd":":","enter":"","register":"","forget":" ?","no_auth":" \/","not":"  ","undef":" ","request":"  ","request2":"  .","on_off":".\/.  -","delete_num":" ","select_num":"    ","insert":"","insert_num":"    ","add_from_file":"    ","add2":"  ","clear_phone":"  ","clear_list":" ","phones_count":"  ","show_by":" :","rows_per_page":"  ","pages":":","add_file":"   ","load":"","choose_txt":"      :","choose_txt_note":"      UTF-8","load_no_more":"      ","already_add":"     ","out_ot":"  ","possible":" ","phone_num":" ","please":",   !","from":"","to":"","format":"  ","send":"   ","on":" ","off":" ","all":" ","24_7":" ","email":" Email. ","blob":"   . ","email_used":"  email  ","not_saved":"  ."},"sets_save":" ","msg_format":{"title":" :","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      ","region":": ","cost":", : ","per_min":"\/","per_min50":" &mdash;     50 ","currency":".","cancel":"","login":":","passwd":":","enter":"","register":"","forget":" ?","no_auth":" \/","not":"  ","undef":" ","request":"  ","request2":"  .","on_off":".\/.  -","delete_num":" ","select_num":"    ","insert":"","insert_num":"    ","add_from_file":"    ","add2":"  ","clear_phone":"  ","clear_list":" ","phones_count":"  ","show_by":" :","rows_per_page":"  ","pages":":","add_file":"   ","load":"","choose_txt":"      :","choose_txt_note":"      UTF-8","load_no_more":"      ","already_add":"     ","out_ot":"  ","possible":" ","phone_num":" ","please":",   !","from":"","to":"","format":"  ","send":"   ","on":" ","off":" ","all":" ","24_7":" ","email":" Email. ","blob":"   . ","email_used":"  email  ","not_saved":"  .","body":" -     ,   :  !\"#$%&()\\'*+,-.\/:;<=>?@[\\\\]^_`{|}~"},"end_reg":{"title":"    ","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      ","region":": ","cost":", : ","per_min":"\/","per_min50":" &mdash;     50 ","currency":".","cancel":"","login":":","passwd":":","enter":"","register":"","forget":" ?","no_auth":" \/","not":" 1","undef":" ","request":"  ","request2":"  .","on_off":".\/.  -","delete_num":" ","select_num":"    ","insert":"","insert_num":"    ","add_from_file":"    ","add2":"  ","clear_phone":"  ","clear_list":" ","phones_count":"  ","show_by":" :","rows_per_page":"  ","pages":":","add_file":"   ","load":"","choose_txt":"      :","choose_txt_note":"      UTF-8","load_no_more":"      ","already_add":"     ","out_ot":"  ","possible":" ","phone_num":" ","please":",   !","from":"","to":"","format":"  ","send":"   ","on":" ","off":" ","all":" ","24_7":" ","email":" Email. ","blob":"   . ","email_used":"  email  ","not_saved":"  .","body":" -     ,   :  !\"#$%&()\\'*+,-.\/:;<=>?@[\\\\]^_`{|}~","col_title":"","complete":" ","sms":" SMS","conf":"","sip":" ","fax":" ","post":"   ","bonus":" , "},"save_fax_errs":{"title":"    ","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      ","region":": ","cost":", : ","per_min":"\/","per_min50":" &mdash;     50 ","currency":".","cancel":"","login":":","passwd":":","enter":"","register":"","forget":" ?","no_auth":" \/","not":" 1","undef":" ","request":"  ","request2":"  .","on_off":".\/.  -","delete_num":" ","select_num":"    ","insert":"","insert_num":"    ","add_from_file":"    ","add2":"  ","clear_phone":"  ","clear_list":" ","phones_count":"  ","show_by":" :","rows_per_page":"  ","pages":":","add_file":"   ","load":"","choose_txt":"      :","choose_txt_note":"      UTF-8","load_no_more":"      ","already_add":"     ","out_ot":"  ","possible":" ","phone_num":" ","please":",   !","from":"","to":"","format":"  ","send":"   ","on":" ","off":" ","all":" ","24_7":" ","email":" Email. ","blob":"   . ","email_used":"  email  ","not_saved":"  .","body":" -     ,   :  !\"#$%&()\\'*+,-.\/:;<=>?@[\\\\]^_`{|}~","col_title":"","complete":" ","sms":" SMS","conf":"","sip":" ","fax":" ","post":"   ","bonus":" , ",1:" ...",2:"  .      TIFF, PDF  JPEG",3:"   ",4:"  ",5:"  "},"err_end_reg":"     , ","err_end_reg2":"  ","end_reg_link":" !","form_errors":{"title":"    ","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      ","region":": ","cost":", : ","per_min":"\/","per_min50":" &mdash;     50 ","currency":".","cancel":"","login":":","passwd":":","enter":"","register":"","forget":" ?","no_auth":" \/","not":" 1","undef":" ","request":"  ","request2":"  .","on_off":".\/.  -","delete_num":" ","select_num":"    ","insert":"","insert_num":"    ","add_from_file":"    ","add2":"  ","clear_phone":"  ","clear_list":" ","phones_count":"  ","show_by":" :","rows_per_page":"  ","pages":":","add_file":"   ","load":"","choose_txt":"      :","choose_txt_note":"      UTF-8","load_no_more":"      ","already_add":"     ","out_ot":"  ","possible":" ","phone_num":" ","please":",   !","from":"","to":"","format":"  ","send":"   ","on":" ","off":" ","all":" ","24_7":" ","email":" Email. ","blob":"   . ","email_used":"  email  ","not_saved":"  .","body":" -     ,   :  !\"#$%&()\\'*+,-.\/:;<=>?@[\\\\]^_`{|}~","col_title":"","complete":" ","sms":" SMS","conf":"","sip":" ","fax":" ","post":"   ","bonus":" , ",1:" ...",2:"  .      TIFF, PDF  JPEG",3:"   ",4:"  ",5:"  ","wrong_format":":    "},"choose_lang":{"title":" ","wrong_number":"  ","wrong_number2":" .    ","no_retail_price":"     ","no_wholesale_price":"     ","nowayout":",      ","locked":"    ","locked2":" ,     ","pin_not_active":",    ","not_enough_money":",     ","no_balance":"        ","no_answer":",   ","no_service":",      ","region":": ","cost":", : ","per_min":"\/","per_min50":" &mdash;     50 ","currency":".","cancel":"","login":":","passwd":":","enter":"","register":"","forget":" ?","no_auth":" \/","not":" 1","undef":" ","request":"  ","request2":"  .","on_off":".\/.  -","delete_num":" ","select_num":"    ","insert":"","insert_num":"    ","add_from_file":"    ","add2":"  ","clear_phone":"  ","clear_list":" ","phones_count":"  ","show_by":" :","rows_per_page":"  ","pages":":","add_file":"   ","load":"","choose_txt":"      :","choose_txt_note":"      UTF-8","load_no_more":"      ","already_add":"     ","out_ot":"  ","possible":" ","phone_num":" ","please":",   !","from":"","to":"","format":"  ","send":"   ","on":" ","off":" ","all":" ","24_7":" ","email":" Email. ","blob":"   . ","email_used":"  email  ","not_saved":"  .","body":" -     ,   :  !\"#$%&()\\'*+,-.\/:;<=>?@[\\\\]^_`{|}~","col_title":"","complete":" ","sms":" SMS","conf":"","sip":" ","fax":" ","post":"   ","bonus":" , ",1:" ...",2:"  .      TIFF, PDF  JPEG",3:"   ",4:"  ",5:"  ","wrong_format":":    ","ru":"","en":"English","he":"?????","cn":"??","es":"Espan~ol","it":"Italiano"}}); 


JSCoreLocale = WClocale.get("main");

_pset.popupWinArr = new Array();

_pset.phone_validation_err = 
{
    'SUCCESS'                   : 0,
    'IP_ADDRESS_FORBIDDEN'      : 1,
    'NOT_FOUND'                 : 2,
    'PIN_IS_NOT_ACTIVE'         : 3,
    'LOCKED_NUMBER_BW_LIST'     : 4,
    'WRONG_NUMBER'              : 5,
    'SERVICE_IS_NOT_ACTIVE'     : 6,
    'NOWAYOUT'                  : 7,
    'NO_RETAIL_PRICE'           : 8,
    'NO_WHOLESALE_PRICE'        : 9,
    'NOT_ENOUGH_DATA'           : 10,
    'NOT_ENOUGH_MONEY'          : 11,
    'BAD_ACCOUNT'               : 12,
    'LOCKED_NUMBER_STOP_PHONE'  : 13
}

function preload_css_images() {
    
    // 2009.09.14 we disable it cause it dont work.. (images downloading 2 times: in this function and on page itself)
    return false;
    
    
    
    
    //dump all the css rules into one string
	var sheets = document.styleSheets;
	var cssPile = '';
	for(var i = 0; i<sheets.length; i++){
		if(!$.browser.msie){
			var thisSheetRules = document.styleSheets[i].cssRules;
			for(var j = 0; j<thisSheetRules.length; j++){
				cssPile+= thisSheetRules[j].cssText;
			}
		}
		else {
		    if (typeof(document.styleSheets[i].cssText) == 'string')
		    {
                cssPile += document.styleSheets[i].cssText;
		    }
		}
	}
	
	//parse string for image urls
	var regexp_icon = new RegExp('icon_.{1,30}_active\.png', "g");
	var imgUrls = cssPile.match(regexp_icon);
	
    // leave only unique values
	var tObj = {};
	for (var i = 0; i < imgUrls.length; i++) 
	{
	    tObj[imgUrls[i]] = 1;
	}
	
	// load images
	var i = 0;
	var path = '';
	var allImgs = [];
	for (var k in tObj)
	{
		allImgs[i] = new Image();
	    //allImgs[i].src = _pset.PATH_TO_IMG +'/'+ k;
	    allImgs[i].src = 'res/images/'+ k;
	}
	
//	var tdiv = document.createElement('div');
//    tdiv.className = 'icon';
//    tdiv.innerHTML = '<div class="icon_1_active"></div>';

}

function window_debug(content, win_name)
{
    if (typeof(win_name) == 'undefined')
    {
        var win_name = 'window_name_' + parseInt(Math.random()*1000);
    }
    var win = window.open('', win_name, 'fullscreen=no, toolbar=no, scrollbars=no, directories=no, status=no, menubar=yes, resizable=yes'); 
    var txt = '';
    if (typeof(content) == 'string')
    {
        txt = content;
    }
    else 
    {
        txt = $.toJSON(content);
    }
	win.document.body.innerHTML = txt;
	win.document.title = win_name;
	win.focus();
}


/*********************************************************************/
/************************ Stack function******************************/

var runStack = new Object;

function addToRunStack(func, eventID, delay)
{
    if (typeof(delay) == 'undefined')  delay = 1000;
    
    function newTimer()
    {
        runStack[eventID].status = 'wait';
        runStack[eventID].timer = setTimeout(function () {
            func();
            runStack[eventID].status = 'done';
        }, delay);
    }
    
    if (typeof(runStack[eventID]) == 'undefined')
    {
        runStack[eventID] = new Object;
        newTimer();
    }
    else
    {
        if (runStack[eventID].status == 'wait')
        {
            clearTimeout(runStack[eventID].timer);
        }
        newTimer();
    }
}

/*********************************************************************/
/************************ PHP functions ******************************/
function trim(str) { 
    if (typeof(str) == 'string') {
    	var re1 = /^\s*/; 
    	var re2 = /\s*$/; 
    	return str.replace(re1, "").replace(re2, "");
    	
    } else {
        return '';
    }
} 

function explode( delimiter, string ) {
	var emptyArray = { 0: '' };
	
	if ( arguments.length != 2
	  || typeof arguments[0] == 'undefined' || typeof arguments[1] == 'undefined' )
	  return null;
	
	if ( delimiter === '' || delimiter === false || delimiter === null )
	  return false;
	
	if ( typeof delimiter == 'function' || typeof delimiter == 'object'
	  || typeof string == 'function' || typeof string == 'object' )
	  return emptyArray;
	
	if ( delimiter === true )
	  delimiter = '1';
	
	return string.toString().split ( delimiter.toString() );
}

function in_array(needle, haystack, strict) {
  var found = false, key, strict = !!strict;
  for (key in haystack) {
      if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
          found = true;
          break;
      }
  }
  return found;
}

function is_array( mixed_var ) {    // Finds whether a variable is an array
  return ( mixed_var instanceof Array );
}

function count( mixed_var, mode ) {    // Count elements in an array, or properties in an object
  var key, cnt = 0;
  if( mode == 'COUNT_RECURSIVE' ) mode = 1;
  if( mode != 1 ) mode = 0;
  for (key in mixed_var){
      cnt++;
      if( mode==1 && mixed_var[key] && (mixed_var[key].constructor === Array || mixed_var[key].constructor === Object) ){
          cnt += count(mixed_var[key], 1);
      }
  }
  return cnt;
}
/************************ PHP functions ******************************/
/*********************************************************************/

/*********************************************************************/
/******************** Position and proportion ************************/
function mousePageXY(e)
{
  var x = 0, y = 0;
  if (!e) e = window.event;
  if (e.pageX || e.pageY) {
    x = e.pageX;
    y = e.pageY;
  }else if (e.clientX || e.clientY) {
    x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
    y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
  }
  return {"x":x, "y":y};
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    // Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    // DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    // IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }

  if ((_pset.LANGUAGE == 'he') && ($.browser.msie))
  {
    scrOfX = -document.body.scrollWidth + $(window).width() + $(window).scrollLeft();

  }
  
  return [ scrOfX, scrOfY ];
}

function getBrowserSizeXY() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number') {
    // Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    // IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    // IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [ myWidth, myHeight ];
}

function getBodyPosition(event, body_x, body_y, offset_x, offset_y){
  var m_x = event.clientX;
  var m_y = event.clientY;
  var scroll_xy = getScrollXY();
  var scroll_x = scroll_xy[0];
  var scroll_y = scroll_xy[1];
  var browser_x = $(window).width();
  var browser_y = $(window).height();
  var body_left = 0;
  var body_top = 0;
  
  if((body_x + m_x + offset_x) > browser_x)
    offset_x -= (body_x + m_x + offset_x) - browser_x + 3;
  if((m_x + offset_x) < 0)
    offset_x -= m_x + offset_x;
  if((body_y + m_y + offset_y) > browser_y)
    offset_y -= (body_y + m_y + offset_y) - browser_y + 3;
  if((m_y + offset_y) < 0)
    offset_y -= m_y + offset_y;    
  
  body_left = m_x + scroll_x + offset_x;
  body_top = m_y + scroll_y + offset_y;
  
  return [ body_left, body_top ];
}

// Detecting coords of the element
function getBounds(element)
{
  /*var left = element.offsetLeft;
  var top = element.offsetTop;

	var scroll_xy = getScrollXY();
  var scroll_x = scroll_xy[0];
  var scroll_y = scroll_xy[1];
	
  for (var parent = element.offsetParent; parent; parent = parent.offsetParent)
 {
    left += parent.offsetLeft;
    top += parent.offsetTop;
  }
	
	var child = element.parentNode;
  var leftOf = 0;
  var topOf = 0;   	
	while (child) {
    if (child.parentElement) {
      child = child.parentElement;
    } else if (child.parentNode) {
      child = child.parentNode;
    } else {
			break;
    }
		if (typeof(child.offsetLeft) == 'undefined'
		 || typeof(child.offsetTop) == 'undefined'
		 || typeof(child.scrollLeft) == 'undefined'
		 || typeof(child.scrollTop) == 'undefined')
		 continue;
		
    leftOf += child.scrollLeft;
    topOf += child.scrollTop;		
  }

	left -= leftOf - scroll_x;
	top -= topOf - scroll_y;	*/
	
	var offset = $(element).offset();
	var left = offset.left;
	var top = offset.top;

	if ((_pset.LANGUAGE == 'he') && ($.browser.msie))
 	{	
 		//alert(left+' '+document.body.scrollWidth+' '+element.offsetWidth); 
 	    left = document.body.scrollWidth - left + element.offsetWidth;
 	    //alert(left);
 	}
	
  return {
    left:   left,
    top:  top,
    right:  left + element.offsetWidth,
    bottom: top + element.offsetHeight,
    width:  element.offsetWidth,
    height: element.offsetHeight
  };
}

/******************** Position and proportion ************************/
/*********************************************************************/

function setCookie (name, value, expires, path, domain, secure) {
  document.cookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
		  offset += search.length;
		  end = cookie.indexOf(";", offset)
		  if (end == -1) {
		    end = cookie.length;
		  }
		  setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

function isParent(child, parent) {
	if (!child || !parent) {
	  return false;
	}
	try {
		while (true) {
		    if (child == parent) {
		      return true;
		    }
		    if(typeof(child) != 'object')
		    	return false;
		    if (child.parentElement) {
		      child = child.parentElement;
		    } else if (child.parentNode) {
		      child = child.parentNode;
		    } else {
		      return false;
		    }
		}
	} catch (e) {
		return false;
	}
}

var globalEval = function(sScript)
{
    if (window.execScript)
        return window.execScript(sScript, 'javascript');
    else
        return window.eval(sScript);
}
/*************************************************************************/
/************************** check / convert stuff ************************/
function checkDateTime(type, str) {
	if(typeof(str) == "undefined")
		return false;
	str = trim(str);
	if(str == '')
		return false;
	if(typeof(type) == "undefined" || (type != 'date1' && type != 'date2' && type != 'time')) 
		type = 'date1';
	
	switch (type)
	{
		case 'date1': // dd.mm.yyyy
			var mask = /^\d{2}\.\d{2}\.\d{4}$/;
			if (mask.test(str))
			{
		    var day = str.substr(0, 2);
	      var month = str.substr(3, 2);
	      var year = str.substr(6, 4);
	
	      if (day >= 1 && day <= 31 && month >= 1 && month <= 12 && year >= 1999 && year <= 2019)
	        return true;
	      else 
	        return false;
			} 
			else
		    return false;
			break;
		
		case 'date2': // yyyy-mm-dd
			var mask = /^\d{4}\-\d{2}\-\d{2}$/;
			if (mask.test(str))
			{
		    var year = str.substr(0, 4);
	      var month = str.substr(5, 2);
	      var day = str.substr(8, 2);
	      
	      if (day >= 1 && day <= 31 && month >= 1 && month <= 12 && year >= 1999 && year <= 2019)
	        return true;
	      else 
	        return false;
			} 
			else
		    return false;
			break;
		
		case 'time': // hh:mm
			var mask = /^\d{2}\:\d{2}$/;
			if (mask.test(str))
			{
		    var hours = str.substr(0, 2);
	      var minutes = str.substr(3, 2);
	
	      if (hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59)
	        return true;
	      else 
	        return false;
			} 
			else
		    return false;
			break;
			
		default: 
			return false;
	}
}

function convertDate(date_str, direction) {
	// direction: true => 31.01.2009 -> 2009-01-31 / false => 2009-01-31 -> 31.01.2009
	if(typeof(date_str) == "undefined" || (date_str == ''))
		return 0;
	if(typeof(direction) == "undefined")
		direction = true; 
	
	if(direction == true){
		var date_arr = explode('.', date_str);
		if(date_arr.length == 3)
			var date_new_str = date_arr[2]+'-'+date_arr[1]+'-'+date_arr[0];
	  else
	  	var date_new_str = date_str;
	}else{
		var date_arr = explode('-', date_str);
		if(date_arr.length == 3)
	    var date_new_str = date_arr[2]+'.'+date_arr[1]+'.'+date_arr[0];
	  else
	  	var date_new_str = date_str;
	}
	
	return date_new_str;
}

function calFixTime(time_str) {
	if(typeof(time_str) == "undefined" || (time_str == ''))
		return 0;
	var time_arr = explode(':', time_str);
	if(time_arr.length == 2){
		var hour = parseInt(time_arr[0]);
		if(isNaN(hour))
			return 0;
		if(hour < 10)
			hour = '0'+hour;
		var minute = parseInt(time_arr[1]);
		if(isNaN(minute))
			return 0;
		if(minute < 10)
			minute = '0'+minute;
		var time_new_str = hour+':'+minute;
	}else
	 	var time_new_str = time_str;
	return time_new_str;
}

function check_correct_field(field_type, field_value)
{
	val = trim(field_value);

	switch (field_type)
	{
		case 'email':
		var mask = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
		if (!mask.test(val))
		{
			alert('Bad E-Mail');
			return false;
		}
		break;

		case 'icq':
		var mask = /^\d{1,3}\-?\d{1,3}\-?\d{1,3}$/;
		if (!mask.test(val))
		{
			// alert('Bad ICQ number');
			return false;
		}
		break;
		case 'url':
			var reg_good = /(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)/;
			var reg_bad = /(\[|\])+/gi;
	
			if (!reg_good.test(val) || reg_bad.test(val))
			{
				// alert('Bad URL: '+ val);
				return false;
			}
		break;
		
		case 'time':
		var mask = /^\d{2}\:\d{2}$/;
		if (mask.test(val))
		{
		    var hours = val.substr(0, 2);
            var minutes = val.substr(3, 2);
            
            if (hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59)  {
                return true;
            } 
            else 
            {
                return false;
            }
		} 
		else
		{
            
		    return false;
		}
		break;

	}
	return true;
}
/************************** check / convert stuff ************************/
/*************************************************************************/
function isElemSelected(obj) {
	obj.focus();
	
	if (document.selection) 
	{
	  var s = document.selection.createRange(); 
	  if (s.text)
		  return true;
	}
	else if (typeof(obj.selectionStart)=="number")
	 {
	   if (obj.selectionStart!=obj.selectionEnd)
	     return true;
	 }

	return false;
}

function keyDownInTime(el, event)
{
  var keycode = event.keyCode;
  var inpLenght = el.value.length;
  var inpValue = el.value;

  if(keycode == 0)
  	return false;
  
  // 37 - "<-" / 39 - "->" / 46 - "Del" / 8 - "BackSp" / 48-57 - "0-9" / 96-105 - "0-9 NumPad"
  if((keycode < 48 && keycode != 8 && keycode != 9 && keycode != 37 && keycode != 39 && keycode != 46) ||
  		(keycode > 57 && keycode < 96) || keycode > 105) {
  	return false;
  }
  
  if(keycode == 9)
  	return true;
  	
  if (inpLenght == 2 && keycode != 46) {
    inpValue = inpValue + ":";
    el.value=inpValue;
  }
  if (inpLenght > 4) {
  	if(keycode == 46 || keycode == 37 || keycode == 39)
  		return true;
  	if(isElemSelected(el) == true)
  		return true;
  	if(keycode == 8)
  		return true;
  	return false;
  }
  return true;
}

function keyUpInTime(el, event)
{
  var keycode = event.keyCode;
  var inpLenght = el.value.length;
  var inpValue = el.value;

  if (inpLenght > 2 && inpValue[2] != ':') {
  	inpValue = inpValue.replace(/:/, "");
  	var str_before = inpValue.slice(0,2);
  	var str_after = inpValue.slice(2);
  	inpValue = str_before.concat(":", str_after)
  	el.value=inpValue;
  	inpLenght = el.value.length;
  }
  	
  if (inpLenght == 2) {
  	if (keycode == 8 || keycode == 46) {
      inpValue = inpValue.slice(0,1);
      el.value=inpValue;
    } else {
	    inpValue = inpValue + ":";
	    el.value=inpValue;
    }
  }
  return true;
}

function removeFormSpecialFormatting(jElem)
{
    jElem.removeClass('form_warning');
    jElem.removeClass('form_help_text');
    
    // jElem.css('color', '');
}

function setFormFormattingHelpText(jElem)
{
    removeFormSpecialFormatting(jElem);
    jElem.addClass('form_help_text');
}

function setFormFormattingWarning(jElem)
{
    checkIfTabHidden(jElem);
    
    removeFormSpecialFormatting(jElem);
    jElem.addClass('form_warning');
}

function checkEmptyIn(input, defVal) 
{
    if (input.value == defVal)
    {
        input.value = '';
        removeFormSpecialFormatting($(input));
    }
    
    //$.showMsgBT('checkEmptyIn', '' , 'conf_save','alert', 500);
}

function checkEmptyOut(input, defVal)
{
    if (!trim(input.value))
    {
        input.value = defVal;
        setFormFormattingHelpText($(input));
    }
    else if (input.value != defVal) 
    {     
        //alert('remove formatting' + input.value + ' V ' + defVal)
        removeFormSpecialFormatting($(input));
    }
    
    //$.showMsgBT('checkEmptyOut', '' , 'conf_save','alert', 500);
}


function checkIfTabHidden(jElem)
{
    if (jElem.length)
    {
        
        if (!$(jElem).is(':visible'))
        {
            var jTab = $(jElem).parents().filter('[id^="tab_"]');
            if (jTab.length)
            {
                var tabName = jTab[0].id.substr(4, jTab[0].id.length);
                toggle_tab(tabName);
            }
        }
    }
}


function generateNewNum1() 
{
    if (typeof(_pset.tSequence) == 'undefined') {
        _pset.tSequence = 0;
    }
    return ++_pset.tSequence;
}

function generateNewNum(seq_name) 
{
    if (typeof(_pset.tSequences) == 'undefined') {
        _pset.tSequences = new Array();
    }
    
    if (typeof(_pset.tSequences[seq_name]) == 'undefined') {
        _pset.tSequences[seq_name] = 0;
    }
    
    return ++_pset.tSequences[seq_name];
}


function tableGetNewRow(id_table)
{
    var jTable = $('#' + id_table);
    
    if (typeof(_pset.js_control_table[id_table].default_row) != 'undefined')
    {
        var jRow = _pset.js_control_table[id_table].default_row.clone();
//        alert('from cache')
    }
    else
    {
        var jRow = jTable.find('tr:nth-child(2)').clone();    
    }
    
    var new_id, new_id_text; 
    
    do
    {
        new_id = generateNewNum('s' + id_table);
        new_id_text = 'new_' + new_id;
    } 
    while ($('#' + id_table + '_tr_' + new_id_text).length);
     
    
    var jTdArr = jRow.find("td");
    var jTdArr = jRow.find("td:gt(0):lt(" + jTdArr.length + ")");
    var control_table = _pset.js_control_table[id_table];
    
    jTdArr.each(function(n)
    {
        var k = n;
        
        var jControlEl = $(this).find("input, select");
        var jImg = $(this).find("img");
      if (jControlEl.length) 
        {
            var tSearch = jControlEl[0].name.match(/(^.*)\[[^\[]+$/);
            if (tSearch.length)
                var tName = tSearch[1];
            else
                var tName = jControlEl[0].name;
            
    	    var newName = tName + '[' + new_id_text + ']';
    	   
    	    jControlEl[0].name = newName;
    	    jControlEl[0].id   = newName;
    	    
    	    if (typeof(control_table.fields[k].is_iterative) != 'undefined' && control_table.fields[k].is_iterative == 1)
    	    {
                var jTdInLastTr = jTable
                    .find('tr:nth-child(' + (jTable.find("tr").length - 1) + ')')
                    .find('[id^="' + tName + '"]');
                
                jControlEl[0].value = parseInt(jTdInLastTr[0].value) + 1;
    	    }
    	    else 
    	    {
    	        jControlEl[0].value = control_table.fields[k].new_item_default_value;
    	    }
    	    
    	    if (typeof(control_table.fields[k].bind_help_text) != 'undefined' && control_table.fields[k].bind_help_text == 1)
    	    {
    	        setFormFormattingHelpText(jControlEl);
    	    }
    	    else
    	    {
    	        removeFormSpecialFormatting(jControlEl);
    	    }
        }
        else if (jImg.length)
        {
            //alert(new_id_text)
        }
        else
        {
            //alert(k);
            //this.innerHTML = control_table.fields[k].new_item_default_value;
            
            //tdArr[k].innerHTML = control_table.fields[k].new_item_default_value;
        }
        
	});
	
	jRow.find('input:checkbox').attr({'checked' : true});
	
	jRow[0].id = id_table + '_tr_' + new_id_text;
	
	
	var jActionImg = jRow.find("td a img");
	
    var aHTML = '<a href="#" onclick="tableDeleteRow(\'' + id_table + '\', \'' + new_id_text + '\'); return false;">';
    aHTML += '<img src="' + _pset.PATH_TO_IMG + '/element_delete.png" width="16px" height="16px"></a>';
    jActionImg[0].parentNode.parentNode.innerHTML = aHTML;
    
    //alert(jRow.find("a").length)
    //alert(aHTML)
    
    var jChangeTd = jRow.find("td[id^=" + id_table + "_td]");
    if (jChangeTd.length)
        jChangeTd[0].id = id_table + '_td_' + new_id_text;
       
//    var ret = 
//    {
//        'jRow'            : jRow,
//        'jTable'          : jTable,
//        'new_id_text'     : new_id_text
//    };
//    return ret;

    return ret =
    {
        'jRow'            : jRow,
        'jTable'          : jTable,
        'new_id_text'     : new_id_text
    };
}

function getElemsToValidate(id)
{
    var id = id || 'ph_number';
    var jElemsToValidate = $('input[id^="' + id + '"]')
            .filter(function() { 
                if (!$(this).attr('readonly'))
                    return $(this); 
            });
            
    return jElemsToValidate;
}


function tableInsertRow(id_table) 
{
    var oRow = tableGetNewRow(id_table);
    var jTable = oRow.jTable;
    var jRow = oRow.jRow;
    var new_id_text = oRow.new_id_text;
    
    jTable.find('tr:last-child').before(jRow);
    
    tableCorrectStyle(id_table);
    
    if (typeof(_pset.ajax_validation) != 'undefined')
    {
        _pset.ajax_validation()    
    }
    else
    {
        install_ajax_validation('callme', false, getElemsToValidate(), false); 
    }
    
    
    var time_table = _pset.js_control_table[id_table].time_table;
    if (typeof(time_table) != 'undefined')
    {
        time_table[new_id_text] = new Object();
        
        for (var tt_key in time_table)
        {
            if (sizeof(time_table[tt_key]))
            {
                for (var field_name in time_table[tt_key])
                {
                    time_table[new_id_text][field_name] = '';
                    
                    if (field_name == 'ph_start_time')
                        time_table[new_id_text]['ph_start_time'] = _pset.conf.DEFAULT_CALLME_START_TIME;
                        
                    if (field_name == 'ph_stop_time')            
                        time_table[new_id_text]['ph_stop_time'] = _pset.conf.DEFAULT_CALLME_STOP_TIME;
                    
                }
                break;
            }
        }
        
        
        
        bind_time_table(id_table);
    }
}

function tableDeleteRow(id_table, id_row) 
{
    var jTable = $('#' + id_table);
    var rows_count = $('tr[id^="' + id_table + '_tr_"]').length;
    
    if ( rows_count  > 1) {
        
        var jRow = jTable.find('tr[id="' + id_table + '_tr_' + id_row + '"]').remove();
        
        tableCorrectStyle(id_table);
        
        var time_table = _pset.js_control_table[id_table].time_table;
        if (typeof(time_table) != 'undefined')
        {
            time_table[id_row] = new Array();
        }
    }
    else if (rows_count == 1)
    {
        var can_del_rows = _pset.js_control_table[id_table].can_delete_all_rows;
        if (typeof(can_del_rows) != 'undefined' && can_del_rows == 1)
        {
            removeTable(id_table);
        }
    }
    
//    alert($.toJSON(_pset.time_table))
}

function tableCorrectStyle(id_table)
{
    var jTable = $('#' + id_table);
    jTable.find("tr:even").attr({'className' : 'bg_grow'});
    jTable.find("tr:odd").attr({'className' : ''});
}

function addExistedTable(id_table)
{
//    var jDiv = $('#' + id_table + '_div');
//    var ct = _pset.js_control_table[id_table];
//    if (jDiv.length && typeof(ct) != 'undefined' && typeof(ct.table_dump) != 'undefined')
//        jDiv[0].innerHTML = ct.table_dump;


    _pset.js_control_table[id_table].is_empty = 0; 
    
    toggle_el(id_table + '_div');
    toggle_el(id_table + '_a'); 
    toggle_el(id_table + '_h');
}

function removeTable(id_table)
{
    _pset.js_control_table[id_table].is_empty = 1;
    //_pset.js_control_table[id_table].basic_content = 1;
    //_pset.js_control_table[id_table].table_dump = jTable[0];
    
    $('#' + id_table + '_div').hide();
    $('#' + id_table + '_a').show();
    $('#' + id_table + '_h').hide();
}



sizeof = function(obj) 
{
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) 
        {
            //alert('key='+key);
            size++;
        }
    }
    return size;
};

// Get the size of an object
//var size = Object.size(myArray);


//



//function radio_iterator(jElem)
//{
//    for (var i=0; i<jElem.length; i++)
//    {
//        //Elem.options[i]
//        jElem.options[i]
//    }
//    
//    
//      for (var k=0; k<optLength; k++)
//        {
//            //alert('op_counter='+op_counter+'\noptions[op_counter]='+jWeekday[0].options[op_counter]);
//            //alert(jWeekday[0].options[op_counter].value + ' v ' +time_table[id_row].ph_weekday_type)
//            //if (jWeekday[0].options[op_counter].value == time_table[id_row].ph_weekday_type)
//            
//            //alert('jWeekday[0].options['+k+'].value='+jWeekday[0].options[k].value+'\njWeekday[0].options['+k+']='+jWeekday[0].options[k])
//            
//            if (jWeekday[0].options[k].value == time_table[id_row].ph_weekday_type)
//            {
//                //alert(k)
//                jWeekday[0].selectedIndex = k;
//                changed = 1;
//                break;
//            }
//        }
//        if (!changed) jWeekday[0].selectedIndex = 0;
//        
//        
//        for (var field_name in time_table[id_row])
//}







function tooltips_init() {
	
	var tooltips = new Array();
	var tooltips = jQuery('[id^="tooltip_"]');

	for (var i=0; i<tooltips.length; i++) {
		var part_id = tooltips[i].id.replace(/^tooltip_/i, "");

		//alert(part_id);
		$("#area_"+part_id).jHelperTip({
			dC:"#tooltip_"+part_id,
			trigger: "click",
			autoClose: true,
			opacity: 0.5
		});

	}
}

function alt_tooltips_init() {
    $("#area_alg").jHelperTip({
        //trigger: "hover", 
        trigger: "click",
        source: "attribute", 
        attrName: "alt", 
        opacity: 0.8, 
        autoClose:true,
        aC: "#jHelperTipDataContainer" 
    });
}


function displayNotifyMessage(message) {

	//$.blockUI({ message: $('#form_window'), fixWindow: true, css: { backgroundColor: '#fff', position: 'fixed', top: top_pos, left: left_pos } });
	
	
	window_width = 350;
	var screen_pos = getBrowserSizeXY();
	var top_pos = (screen_pos[1])/2;
	var left_pos = ($(document).width()	- window_width)/2;
	

	jQuery.blockUI(
	   {
	        message: message,
            fixWindow: true, 
            applyPlatformOpacity: true,
            css: 
            {
        		top: top_pos,
        		left: left_pos,
        		width: window_width + 'px',
        		'text-align' : 'left',
        		border: 'none',
        		padding: '15px',
        		backgroundColor: '#000',
        		'-webkit-border-radius': '10px',
        		'-moz-border-radius': '10px',
        		
        		opacity: '0.7',
                '-moz-opacity': '0.7',
                '-khtml-opacity': '0.7',
                filter: 'progid:DXImageTransform.Microsoft.Alpha(opacity=70)',
        		
        		color: '#fff'
            }
	   }
    );
    	
	setTimeout(jQuery.unblockUI, 3000);

}



// ===========================================================================================================================================


function showPic(img_src, comment_text, imx_g, img_y) {
	
	$('#block_window_img_div').get(0).innerHTML = '<img id="block_window_img" src="' + img_src + '">';
	if (comment_text) {
		$('#block_window_img_comment').get(0).innerHTML = comment_text;
	}
	// alert('pre request');
	$.preload('#block_window_img', {

		onRequest:request,
		onComplete:complete,
		onFinish:finish,
		// placeholder:'http://aflesler.webs.com/img/placeholder.jpg',//this is the
		// really important option
		// notFound:'http://aflesler.webs.com/img/notfound.jpg',//optional image if
		// an image wasn't found
		threshold:1 // '1' is the default, how many at a time, to load.
	});
}

// -------------------------------------------------------------
// Detecting what css-properies for current object
function getStyleProperty(el, cssProperty)
{
    var cssPerlProperty = ""
    var capitalize = false
    for (var i = 0; i < cssProperty.length; i++){
    	if (capitalize) {
    		capitalize = false
    		cssPerlProperty += cssProperty.substr(i,1).toUpperCase()
    	} else {
    		if (cssProperty.substr(i,1) == "-")
    			capitalize = true
    		else
    			cssPerlProperty += cssProperty.substr(i,1)
    	}
    }
    
    if (el.currentStyle){
    	return el.currentStyle[cssPerlProperty]
    }
    
    if (document.defaultView && document.defaultView.getComputedStyle
    		         && document.defaultView.getComputedStyle(el, null)
    		         && document.defaultView.getComputedStyle(el, null).getPropertyValue)
    	return document.defaultView.getComputedStyle(el, null).getPropertyValue(cssProperty);
    return 0;
}
// -------------------------------------------------------------
//getStyleProperty = function(el,cssProperty){
//	return Object.getStyleProperty.call(el,cssProperty);
//}
// ------------------------------------------------------------------

function cancel(evt)
{
	evt = ( evt || window.event );
	key = ( evt.keyCode || evt.charCode || evt.which );
	if ( key == 3 || key == 9 || key == 13)
	{
		// alert(evt);
		evt.preventDefault();
		evt.stopPropagation();
	}
}


// //////////////////////////////////////////////////////////////////////////////////////////////////


// Just sample..

//var myJSONObject = {
//	"bindings": 
//	[
//        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
//        {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
//        {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
//    ]
//};


function show_div(id_arr) {
	for (var id in id_arr) {
		$('#' + id_arr[id]).show();
	}
}

function hide_div(id_arr) {
	for (var id in id_arr) {
		$('#' + id_arr[id]).hide();
	}
}

function change_form_view_ext(id_string) {
	if (typeof(id_string) == 'undefined') {
		id_string = '';
	}
	
	
	
	$('#user_form > [id^="frm_' + id_string + '"][id$=_hidden].frm-line').toggle();
	
	
	$('#user_form > div > div > [id^="div_edit_' + id_string + '"]div').toggle();
	
	
	$('#user_form > div > div > [id^="div_nonedit_' + id_string + '"]div').toggle();
	
	
	$('#user_form > div > div > [id^="div_button_change_' + id_string + '"]div').toggle();
	
	
	$('#user_form > div > div > [id^="div_button_save_' + id_string + '"]div').toggle();
	
}

function j_test() {
	
	//alert ($('#user_form > [id^="frm_user_school_0"][vasya="is_hidden"].frm-line').html());
}



function setup_calendar() {
    
// Calendar.setup(
// {
// flat : "calendar-container" // ID of the parent element
//  
// }
// );


    
    if ($('#input_date_id').length) {
    	Calendar.setup({
            inputField     :    'input_date_id',
            // ifFormat : '%d.%m.%Y',
            ifFormat       :    '%Y-%m-%d, %H:%M',
            // ifFormat : '%d %B %Y, %H:%M',
            showsTime      :    true,
            button         :    'trigger_date',
            align          :    'TR',
            singleClick    :    true
        });    
    }
    
    if ($('#input_date_id2').length) {
        Calendar.setup({
            inputField     :    'input_date_id2',
            // ifFormat : '%d.%m.%Y',
            ifFormat       :    '%Y-%m-%d, %H:%M',
            showsTime      :    true,
            button         :    'trigger_date2',
            align          :    'TR',
            singleClick    :    true
        });
    }
}



function doLoad(value) {
    // Create new JsHttpRequest object.
    var req = new JsHttpRequest();
    // Code automatically called on load finishing.
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            // Write result to page element (_RESULT become responseJS).
            // document.getElementById('ans').innerHTML = req.responseJS.html;
            if (req.responseJS.error_msg) {
            	$('#personal_block').get(0).innerHTML += req.responseJS.error_msg;
            	
            } else {
            	$('#personal_block').get(0).innerHTML = req.responseJS.html;
            }
                
            // Write debug information too (output become responseText).
            document.getElementById('debug').innerHTML = req.responseText;
        }
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, 'backend_personal.php', true);
    // Send data to backend.
    req.send( { the_form: value, "action" : "photo" } );
}





/* ---------------------------------------------------------------------------------- */
/*
 * 
 * Webcabinet
 * 
 */
/* ---------------------------------------------------------------------------------- */


function block_test () {
	
	$('#block_window_img_comment').html($('#addr_book').html());
	
	var browser_XY = getScrollXY();
			
	var top_pos = browser_XY[1];
	var left_pos = ($(document).width()	- $('#block_window').width())/2;
	
	
	$.blockUI({ message: $('#block_window'), 
	   css: { 
    	    backgroundColor: 'white', 
    	    position: 'absolute',
    	    padding: 10,
    	    margin: 10,
    	    top: top_pos, 
    	    left: left_pos 
	   } 
	});
	
}

function unblock_test () {
	$.unblockUI()
}


var wcNamespace = {};


function add_from_book (event, num) {
    wcNamespace.add_to = num;
	initContextMessage(event, 'addr_book');
}

function name_for_phone(phone)
{
    if (typeof(_pset.addr_book_personal) != 'undefined' && _pset.addr_book_personal.length)
    {
        for (var i in _pset.addr_book_personal)
        {
            if (_pset.addr_book_personal[i].phone == phone)
                return _pset.addr_book_personal[i].name;
        }
    }
    
    if (typeof(_pset.addr_book) != 'undefined' && _pset.addr_book.length)
    {
        for (var i in _pset.addr_book)
        {
            if (_pset.addr_book[i].phone == phone)
                return _pset.addr_book[i].name;
        }
    }
    
    return '';
}

function phone_for_name(name)
{
    if (typeof(_pset.addr_book) != 'undefined' && _pset.addr_book.length)
    {
        for (var i in _pset.addr_book)
        {
            if (_pset.addr_book[i].name == name)
                return _pset.addr_book[i].phone;
        }
    }
    
    return '';
}


function add_contact(name, phone, num_id, options) {
    
    $jInputPhone = $('#input_user_phone_' + wcNamespace.add_to);
    $jInputName = $('#input_user_name_' + wcNamespace.add_to);
    
    if (typeof(options) != 'undefined')
    {
        if (options == 'bind_fields')
        {
            if ($jInputName.length)
            {
                $jInputName.html(name);
                $jInputName.val(name);
                //$jInputName[0].value = name;
            }
                
            if ($jInputPhone.length)
            {
                $jInputPhone.val(phone);
                //$jInputPhone[0].value = phone;
            }
        }
    }
    else 
    {
        if ($('#is_from_adress_book_'+ wcNamespace.add_to).length) {
            $('#is_from_adress_book_'+ wcNamespace.add_to).get(0).value = num_id;
        }
        
        $jInputPhone.hide();
        $jInputName.hide();
        
        $('#user_name_'+ wcNamespace.add_to).html(name);
        $('#user_phone_'+ wcNamespace.add_to).html(phone);
    }
    
    $jInputPhone.focus();
    $jInputPhone.blur();
    
    $.unblockUI();
}


function add_contact_personal(name, phone) {
    
    $jInputPhone = $('#input_user_phone_0');
    if ($jInputPhone.length)
    {
        $jInputPhone.val(phone);
        //$jInputPhone[0].value = phone;
    }
    
    $jInputName = $('#input_user_name_0');
    if ($jInputName.length)
    {
        $jInputName.html(name);
        $jInputName.val(name);
    }

    $jInputPhone.blur();
    
    $.unblockUI();
}

function del_contact(num) {
    
    $('#is_from_adress_book_'+ num).get(0).value = 0;
    
    $('#user_name_'+ num).html('');
    $('#user_phone_'+ num).html('');
    
    $('#input_user_name_'+ num).get(0).value = '';
    $('#input_user_phone_'+ num).get(0).value = '';
    
    $('#input_user_name_'+ num).show();
    $('#input_user_phone_'+ num).show();
}


function choose_personal_phone (event) {
    
	initContextMessage(event, 'personal_phone');
}

function add_personal_phone(phone, input_id) {
    
    if (typeof(input_id) == 'undefined') {
        var input_id = 'input_user_phone_0';
    } 
    
    $('#' + input_id)[0].disabled = '';
    
    if ($('#call_to_root').length) 
    {
        $('#call_to_root')[0].checked = 'checked';
    }
    
    var jquery_input_elem = $('#' + input_id);
    jquery_input_elem[0].value = phone;
    
    jquery_input_elem[0].focus();
    jquery_input_elem[0].blur();
    
    $.unblockUI();
}


function add_text_to_input(phone, name, input_pos) {
// $('#' + id_prefix + '_name')[0].value = name;
// $('#' + id_prefix + '_number')[0].value = phone;
    var jName = $('#input_user_name_' + input_pos);
    var jPhone = $('#input_user_phone_' + input_pos);
    
    jName[0].value = name;
    jPhone[0].value = phone;
    
    jPhone[0].focus();
    jPhone[0].blur();
    
    $.unblockUI();
}


function add_calendar(id_input, id_icon, options) {

    if (typeof(options) == 'undefined') {
        
        var options = 
            {
                constrainInput: true,
                showAnim: 'fadeIn'
            }
    }
    
    $('#' + id_input).datepicker(options)
            
    $('#' + id_icon)
        .css('cursor', 'pointer')
        .bind(
            'click',
            function () {
                $('#' + id_input).datepicker("show");        
            }
        )
        
}


function JsHttpRequest_debug(result, errors)
{
    if (0) {
        $('#JsHttpRequest_debug').show();
        
        document.getElementById("debug").innerHTML += errors;
        document.getElementById("ans").innerHTML = result;
    }
}










function correctPNG() // correctly handle PNG transparency in Win IE 5.5 or
											// higher.
{
	for(var i=0; i<document.images.length; i++)
	{
		var img = document.images[i]
		var imgName = img.src.toUpperCase()
		if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
		{
			var imgID = (img.id) ? "id='" + img.id + "' " : ""
			var imgClass = (img.className) ? "class='" + img.className + "' " : ""
			var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
			var imgStyle = "display:inline-block;" + img.style.cssText
			if (img.align == "left") imgStyle = "float:left;" + imgStyle
			if (img.align == "right") imgStyle = "float:right;" + imgStyle
			if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
			var strNewHTML = "<span " + imgID + imgClass + imgTitle
				+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
				+ " filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
				+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
			img.outerHTML = strNewHTML
			i = i-1
		}
	}
}






var preload_image_object;



/* ================================================================== */

function is_array(val)
{
    if (typeof(val) != 'undefined' && sizeof(val))
        return true;
    else
        return false;
}


function showValidationErrors(errors)
{
    var RANGE_ERR = 3
    var MISSING_DATA = 5;
    
    if (!is_array(errors))
        return false;
    
    if (is_array(errors.single))
    {
        for (var el_name in errors.single)
        {
            var jSingleEl = $('[name="' + el_name + '"]');
            if (jSingleEl.length)
                setFormFormattingWarning(jSingleEl);    
        }
    }
    
    if (is_array(errors.tables))
    {
        var id_was_binded = null;
        for (var table_name in errors.tables)
        {
            var table_errors = errors.tables[table_name];
            
            for (var rowIndex in table_errors)
            {
                var row_errors = table_errors[rowIndex];
                
                for (var alias in row_errors)
                {
                    if (id_was_binded)
                    {
                        var jElem = $('[name="' + table_name + '\\[' + alias + '\\]\\[' + rowIndex + '\\]"]');
                    }
                    else if (id_was_binded == false)
                    {
                        var jElem = $('[name="' + alias + '[' + rowIndex + ']"]');
                    }
                    else
                    {
                        var jElem = $('[name="' + table_name + '\\[' + alias + '\\]\\[' + rowIndex + '\\]"]');
                        if (jElem.length)
                        {
                            var id_was_binded = true;
                        }
                        else
                        {
                            var id_was_binded = false;
                            jElem = $('[name="' + alias + '[' + rowIndex + ']"]');
                        }
                    }
                    setFormFormattingWarning(jElem);
                }
            }    
        }
    }
    
}



/* Currently not used */
//function install_ajax_validation_conf() {
//
//    $('[id^="input_user_phone"]').bind(
//		'blur',
//		function()
//		{
//		    if (trim(this.value) != '') {
//                validatePhoneNumber(this.value, 0, 'confValidatePhoneNumberCallback', $(this));
//		    }
//		}
//	)
//}   

function validatePhoneNumber (fsnumber, keyword, result_as_arr, noauth, callback_function, callback_function_params, service_id) {
    
    fsnumber = trim(fsnumber);
    var reqObj = {
        'action'            : 'validate_num',
        'fsnumber'          : fsnumber,
        'result_as_arr'     : result_as_arr,
        'keyword'           : keyword,
        'noauth'            : noauth
    };
    
    if (typeof(service_id) != 'undefined')
    {
        reqObj['service_id'] = service_id;
    }
    
    JsHttpRequest.query(
        _pset.PATH_TO_ROOT + '/backend.php',
        reqObj,
        function(result, errors)
        {  
            //eval(callback_function + '(result, callback_function_params)');
            
            if (typeof(callback_function) == 'object' && callback_function.length)
            {
                for (var i = 0; i < callback_function.length; i++)
                {
                    if (typeof (callback_function[i]) == 'function')
                    {
                        callback_function[i](result, callback_function_params);
                    }
                }
            }
            else 
            {
                callback_function(result, callback_function_params);
            }
        }, 
        false
    );
}

function confValidatePhoneNumberCallback(result, jquery_element_input) {
    
    if (result.error_code == 0) {
        removeWarningForInput(jquery_element_input);
        
    } else {
        setWarningForInput(jquery_element_input, result.error_code);
    }
}

function webCallValidatePhoneNumberCallback(result, params) {
    
    if (!trim(result.region))
    {
        var matches;
        matches = /^sip:.*@(.*)$/i.exec( params.jquery_element_input.val() );
        if ( matches )
        {
            result.region = matches[1];
        }
    }
    
    var id_input = params.jquery_element_input[0].id;
    var phones_correct;
    
    var operation_status = (typeof (result.operation_status) == 'undefined') ? 'ok' : result.operation_status;
    
    if (operation_status == 'no_auth' && !params.noAuth)
    {
        $.blockAuthForm();
        return;
    }
    
    if (result.error_code == 0) {
        _pset.webCall.is_correct_input[id_input] = 1;
        _pset.webCall.price_for[id_input] = result.price;
        
        removeWarningForInput(params.jquery_element_input);
        
        addTariffInfo(params.jquery_element_input, result);
        
        phones_correct = 1;
        for (var i in _pset.webCall.is_correct_input) {
            if (_pset.webCall.is_correct_input[i] == 0) {
                phones_correct = 0;
            }
        }
        
        if (phones_correct) {
            var price_sum = 0;
            for (var i in _pset.webCall.price_for) {
                price_sum += parseFloat(_pset.webCall.price_for[i]);
            }
        }
        
    } else {
        phones_correct = 0;
        setWarningForInput(params.jquery_element_input, result.error_code);    
        
        
        
        _pset.webCall.is_correct_input[id_input] = 0;
        webCallValidatePhoneNumberRemoveInfo(id_input);
    }
    
    if (phones_correct) {
        
        if (params.disable_submit_button) 
        {
            $('#submit_button').attr({disabled : false});
            $('#btnPlanCall').attr({disabled : false});
        }
        
        //var comment_text = 'Стоимость разговора (руб/мин): ' + price_sum;
        //$('#calls_comment').html(comment_text);
        
    } else {
        
        if (params.disable_submit_button)  
        {
            $('#submit_button').attr({disabled : true});
            $('#btnPlanCall').attr({disabled : true});
        }
        
        $('#calls_comment').html('');
    }
}

function webCallValidatePhoneNumberRemoveInfo(id_input) {
    jquery_element_input = $('#' + id_input);
    $('#calls_comment').html('');
    
    removeTariffInfo(jquery_element_input);
}


function setWarningForInput(jInput, error_code, error_text) {
    
    var errs = _pset.phone_validation_err;
    
    if (!jInput.hasClass('form_warning')) 
    {
        if (typeof(error_text) != 'undefined' && error_text !== false)
        {
            var text_msg = error_text;
        }
        else if (typeof(error_code) == 'undefined' || error_code === false)
        {
            var text_msg = JSCoreLocale['button_errs']['wrong_number2'];
        }
        else if (error_code == errs.NO_RETAIL_PRICE)
        {
            var text_msg = JSCoreLocale['button_errs']['no_retail_price'];
        }
        else if (error_code == errs.NO_WHOLESALE_PRICE)
        {
            var text_msg = JSCoreLocale['button_errs']['no_wholesale_price'];
        }
        else if (error_code == errs.NOT_ENOUGH_MONEY)
        {
            var text_msg = JSCoreLocale['button_errs']['no_balance'];
        }
        else if (error_code == errs.LOCKED_NUMBER_STOP_PHONE || error_code == errs.LOCKED_NUMBER_BW_LIST)
        {
            var text_msg = JSCoreLocale['button_errs']['locked2'];
        }
        else
        {
            //alert('code = ' + error_code + 'text = ' + error_text);
            var text_msg = JSCoreLocale['button_errs']['wrong_number2'];
        }
        
        $.showMsgBT(JSCoreLocale['att_title'], text_msg, 'phone_validation','alert', 5000);
        setFormFormattingWarning(jInput);
    }
}

function removeWarningForInput(jquery_element_input) {
    
    removeFormSpecialFormatting(jquery_element_input);
}


function addTariffInfo(jquery_element_input, result) {
    
    if (jquery_element_input.length) 
    {
        if (typeof(result.region) == 'undefined' || typeof(result.price) == 'undefined')
        {
           return;
        }
        
        //var str = "Регион: " + result.region;
        var str = JSCoreLocale['tariff']['region'] + result.region + JSCoreLocale['tariff']['cost'] + result.price +' '+_pset.currency + JSCoreLocale['tariff']['per_min'];
        //alert(typeof(result.price2));
        if (typeof(result.price2) != 'undefined')
        {
            if (result.price2 < result.price)
            {
                //str += ' <font color="red">(' +  result.price2 + ' руб, на тарифном плане "<a href="' + _pset.PATH_TO_ROOT_SCRIPT + '/contacts_pricelist">Старт</a>")</font>';
                str += ' <font color="red"><br/>(' +  result.price2 +' '+ _pset.currency + JSCoreLocale['tariff']['per_min50'] + _pset.currency+')</font>';
            }
        }
        
        if (jquery_element_input[0].id == 'input_user_phone_0') {
            $('#my_direction').html(str);
            
        } else if (jquery_element_input[0].id == 'input_user_phone_1') {
            $('#his_direction').html(str);
        }
    }
}

function removeTariffInfo(jquery_element_input) {
    
    if (jquery_element_input.length) {
        if (jquery_element_input[0].id == 'input_user_phone_0') {
            $('#my_direction').html('');
            
        } else if (jquery_element_input[0].id == 'input_user_phone_1') {
            $('#his_direction').html('');
        }    
    }
}

/**
     * Check if phone validation successed
     *
     * @param text - prefix for IDs of element that was checked. Used in expression $('[id^="' + phones_id_prefix + '"]') Default value is 'input_user_phone'
     * @return bool - true or false 
     */
function check_warning_fields (phones_id_prefix) {
    
    if (typeof(phones_id_prefix) == 'undefined') {
        phones_id_prefix = 'input_user_phone';
    }
    
    var have_bad_fields = false;
	$.each( 
        $('[id^="' + phones_id_prefix + '"]'),
        function(index, item) {
            if (trim($(item)[0].value) && $(item)[0].className.indexOf('form_warning') != -1 && $(item)[0].style.display != 'none') {
                have_bad_fields = true;
            }
        }
    );
    
    return have_bad_fields;
}



function init_swf_clocks() 
{
    for (var i = 1; i <= 4; i++)
    {
        $('#swf_clock_div_' + i).flash(
	    	{
	    		src: 		_pset.PATH_TO_IMG + "/clocks.swf",
	    		width: 		69,
	    		height:		69,
	    		wmode: 'opaque',
	    		flashvars: 
	    		{
	    			GMT:     "0",
	    			Time:    _pset.clocks_time[ i ]
	    		}				
	    	}, 
	    	{ version: 8 }	
	    );
    }
}

function url_from_action(action)
{
    return _pset.PATH_TO_ROOT_SCRIPT + '/' + action;
}

var _left_menu = [];
var k = 0;

for (var i = 1; i <= sizeof(_pset.left_menu); i++) {
    if (_pset.left_menu_pos != _pset.left_menu[i].numpos) {
        _left_menu[k] = _pset.left_menu[i];
        
        if (typeof(_pset.left_menu[i].href) != 'undefined')
        {
            _left_menu[k].url = _pset.left_menu[i].href;
        }
        else
        {
            _left_menu[k].url = url_from_action(_pset.left_menu[i].action);
        }
        
        k++;
    } else {
        _pset.left_menu_num = _pset.left_menu_pos;
    }
}

var menu_pos = _pset.left_menu_num;

function left_menu_change(direction) {
    
    if ($('div.icons_l div.icon').length) {
        
        //if (direction == 'curr') menu_pos = 
        
    	if (menu_pos > _left_menu.length) {
	        menu_pos = 1;
	    }
    	if (menu_pos < 1) {
            menu_pos = _left_menu.length;
    	}
	
		if (direction == 'up') {
	        menu_pos--;
	        if (menu_pos < 1) {
	            menu_pos = _left_menu.length;
	        }
	    
	    } 
	    else 
	    {
	       if (direction == 'down'){
		        menu_pos++;
		        if (menu_pos > _left_menu.length) {
		            menu_pos = 1;
		        }
		    }
	    }
	
        for (var i = 0; i <= 2; i++) {
            
            if (menu_pos + i > _left_menu.length) {
                var menu_item = (menu_pos + i) - 1 - _left_menu.length;
            } else {
                var menu_item = (menu_pos + i) - 1;
            }            
            
            if (_left_menu[menu_item].class_name == 'icon_12') {
                var inside_html = '<span class="day_name">' + _pset.calendar_date.day_name + '</span><span class="day_number">' + _pset.calendar_date.day_number + '</span><span class="month_name">' + _pset.calendar_date.month_name + '</span>' + '<span class="link">'+JSCoreLocale['calendar']+'</span>';
            } else {
                var inside_html =  "<span>" + _left_menu[menu_item].header + "</span>";
            }
            
            if (_left_menu[menu_item].url.length) {
                $('div.icons_l div.icon')[i].innerHTML = "<a href='" + _left_menu[menu_item].url + "' class='" + _left_menu[menu_item].class_name + "'>" + inside_html + "</a>";
                
            } else {
                $('div.icons_l div.icon')[i].innerHTML = "<div class='" + _left_menu[menu_item].class_name + "'>" + inside_html + "</div>";
            }
        }
    
        
    }
    
    return false;
}




// Edit advanced properties tab in the 'Planned conferences'
function WCconf_toggle_adv_properties() {
    $('[id^="tr_property_"]').toggle();
    $('[id^="a_property_"]').toggle();    
}

function toggle_edit_personal(id)
{
    if ($('#' + id).length)
    {
        $('#view_personal_div').toggle();
        $('#' + id).toggle();
    }
}

function list_planned_conf(page_num, conf_id, sorting) {
    
    JsHttpRequest.query(
        _pset.PATH_TO_ROOT + '/backend.php',
		{
			'action'		     : 'planned_conf',
			'page_num'           : page_num,
			'conf_id'            : conf_id,
			'sorting'            : sorting
			
			// 'member_mute' : conf_member_id
		},
		function(result, errors)
		{
			$('#planned_conf_list_div').html(result.html);
		}, 
		true
	); 
}






function toggle_disabled(id) {
    if ($('#' + id)[0].disabled) {
        $('#' + id)[0].disabled = '';
    } else {
        $('#' + id)[0].disabled = 'disabled';
    }
}

var map;
var geocoder;
var marker;



// Установить карту редактирования в созданное окно
function insert_google_map() {

    if (!$('#map_big').length) 
        return false;
        
        
    map = new GMap2(document.getElementById("map_big"));
	// var center = new GLatLng(_pset.coords.latitude, _pset.coords.longitude);
	var center = new GLatLng(55.70781994645101, 37.59315490722656);
	map.setCenter(center, parseInt(15));	
	
	geocoder = new GClientGeocoder();
    
    // map.addControl(new GSmallMapControl());
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());

    
	var comtube_building = new GLatLng(55.70871456200233, 37.597832679748535);
	var markerOptions = {draggable: false}
	marker = new PdMarker(comtube_building, markerOptions);
    map.addOverlay(marker);
    
    // Загружаем данные о местоположении, отображаем его
// $.getScript('http://ws.geonames.org/findNearbyJSON?lat=' +
// marker.getPoint().y + '&lng=' + marker.getPoint().x +
// '&style=full&lang=en&callback=google_map_loadJSON');
//    
//    
// address = 'город Москва, ул. Орджоникидзе, 11';
// geocoder.getLocations(address, addAddressToMap);
    
}



// showLocation() is called when you click on the Search button
// in the form. It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation() {
	
	geocoder.getLocations(address, addAddressToMap);
}


// addAddressToMap() is called when the geocoder returns an
// answer. It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(response) {
	
	if (!response || response.Status.code != 200) {
		alert("Sorry, we were unable to geocode that address");
	} else {
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1],	place.Point.coordinates[0]);
		map.setCenter(point);
		
// marker = new GMarker(point);
// map.addOverlay(marker);
		
		// marker.openInfoWindowHtml(place.address + '<br>' + '<b>Country code:</b>
		// ' + place.AddressDetails.Country.CountryNameCode);
		
		radio_marker = map.getFirstMarker(); 
		radio_marker.setPoint(point);
		
		// var center = new GLatLng(_pset.coords.latitude, _pset.coords.longitude);
		
		radio_marker.openInfoWindowHtml(JSCoreLocale['radio_station']);

		// Загружаем данные о местоположении, отображаем его
    	$.getScript('http://ws.geonames.org/findNearbyJSON?lat=' + radio_marker.getPoint().y + '&lng=' + radio_marker.getPoint().x + '&style=full&lang=en&callback=google_map_loadJSON');
		
		// map.clearOverlays();
		
		// $('#location_adress').get(0).innerHTML = place.address;

	}
}

/**
     * Installs AJAX validation on some specified input elements
     *
     * @param text - keyword for check, sending it to ufXReadTariffs procedure (can be: 'call_me', 'conf', 'webphone')
     * @param bool - flag saying to disable or not button with id='submit'. Default is true.
     * @param object - array of DOM input elements, sended as one jQuery element (e.g. $(some_inputs) or $('input[id^="ph_number"]'))  Default is $('input[id^="input_user_phone"]');
     */
function install_ajax_validation(keyword, disable_submit_button, jInputElements, validateNow, noAuth, service_id, userCallbackFunction, onlyClientCheck, userValidationFunction, returnFullInfo) 
{
    if (typeof (validateNow) == 'undefined')
    {
        var validateNow = true;    
    }
    
    if (typeof (noAuth) == 'undefined')
    {
        var noAuth = 0;    
    }
    else 
    {
        noAuth = !noAuth ? 0 : 1
    }
    
    if (typeof(onlyClientCheck) == 'undefined')
    {
        var onlyClientCheck = false;
    }
    
    if (typeof(service_id) == 'undefined')
    {
        var service_id = false;
    }
    
    if (typeof(userCallbackFunction) == 'undefined')
    {
        var userCallbackFunction = function() {};
    }
    
    if (typeof(disable_submit_button) == 'undefined') 
    {
        var disable_submit_button = true;
    }
    
    if (typeof(jInputElements) == 'undefined') 
    {
        var jInputElements = $('input[id^="input_user_phone"]');
    }
    
    if (typeof(returnFullInfo) == 'undefined')
    {
        var returnFullInfo = 0;
    }
    
    
    _pset.webCall = 
    {
        'is_correct_input' : 
        {
            'input_user_phone_0' : 0, 
            'input_user_phone_1' : 0
        },
        'price_for' : 
        {
            'input_user_phone_0' : 0, 
            'input_user_phone_1' : 0
        } 
    };
	
	this.performValidation = function (inputElem, forceOnlyClientCheck)
	{
	    var _onlyClientCheck;
	    if (typeof(forceOnlyClientCheck) != 'undefined')
	    {
	        _onlyClientCheck = forceOnlyClientCheck;
	    }
	    else
	    {
	        _onlyClientCheck = onlyClientCheck;
	    }
	    
	    inputElem.value = trim(inputElem.value);
	    
	    var doRequest = true;
	    if (inputElem.value == '') 
	    {
	        doRequest = false;
	        removeWarningForInput($(inputElem));
	    }
	    else
	    {
    	    for (var i in _pset.default_text_values) 
    	    {
                if (inputElem.value == _pset.default_text_values[i]) 
    		    {
                    doRequest = false;
                    setFormFormattingHelpText($(inputElem));
                    break;
    		    }     
    	    }
	    }
	    
	    if (!trim(inputElem.id))
        {
            inputElem.id = 'input_id_' + inputElem.name;
        }
        
        
	    
	    if (doRequest)
	    {
            var check = true;
            var checkingObj = false;
            
            if (typeof (userValidationFunction) != 'undefined' && userValidationFunction)
	        {
	            checkingObj = userValidationFunction(inputElem.value);
	            check = checkingObj.res;
	        }
	        else
	        {
	            var checker = new phoneChecker(inputElem.value)
	            
	            check = ( checker.f.standart() || checker.f.externalSip() || checker.f.internalSip() ) ? true : false;
	            //check = ( checker.checkAll() ) ? true : false;
	            if (!check && !checker.checkMinLength()) 
	            {
	                checkingObj = {'reason' : JSCoreLocale['check_num']};
	            }
	            
	        }
	       	       
	        //$.echo('value = ' + inputElem.value + '<br/> check1 = ' + check1 + '<br/>check2 = ' + check2);
	        
	        if (!check)
	        {
	            doRequest = false;
	            if (checkingObj)
	            {
	                setWarning(false, checkingObj.reason);
	            }
	            else
	            {
	                setWarning();
	            }
	        }
	        else
	        {
	            removeWarning();
	        }
	    }
	    
	    
	    
	    if (doRequest && !_onlyClientCheck ) 
	    {
	        
	        
            validatePhoneNumber(
                inputElem.value, 
                keyword,
                returnFullInfo,
                noAuth, 
                [   
                    webCallValidatePhoneNumberCallback,
                    userCallbackFunction
                ], 
                { 
                    'jquery_element_input'   : $(inputElem),
                    'disable_submit_button'  : disable_submit_button,
                    'noAuth'                 : noAuth
                },
                service_id
            )
	    } 
	    
	    function setWarning(error_code, error_text)
	    {
            if (typeof(error_code) == 'undefined') var error_code = false;
            if (typeof(error_text) == 'undefined') var error_text = false;
            
	        setWarningForInput($(inputElem), error_code, error_text); 
	        
	        webCallValidatePhoneNumberRemoveInfo(inputElem.id);
	        _pset.webCall.is_correct_input[inputElem.id] = 0;
	        if (disable_submit_button) 
            {
                $('#submit_button').attr({disabled : true});
                $('#btnPlanCall').attr({disabled : true});
            }
	    }
	    
	    function removeWarning()
	    {
	        removeWarningForInput($(inputElem));
	        
	        _pset.webCall.is_correct_input[inputElem.id] = 1;
            if (disable_submit_button) 
            {
                var havePhones = 1;
                for (var x in _pset.webCall.is_correct_input)
                {
                    if (_pset.webCall.is_correct_input[x] == 0)
                    {
                        havePhones = 0;
                    }
                }
                
                if (havePhones)
                {
                    $('#submit_button').attr({disabled : false});
                    $('#btnPlanCall').attr({disabled : false});
                }
            }
	    }
	    
	}
	var _performValidation = this.performValidation;
	
	jInputElements.blur (function() 
	{
	    _performValidation(this);
    });

    jInputElements.keyup( function() 
    {
        var inputEl = this;
        var length = this.value.length;
        
        if (length > 3)
        {
            addToRunStack(function() { _performValidation(inputEl) }, 'checkPhone' + inputEl.id, 500);
        }
    });
    
    
    //jInputElements.live('blur', performValidation);
    
    if (validateNow)
    {
	   jInputElements.blur();
    }
	
	
//	var jAllInputElements = $('input[type="text"]');
//	var textToReplaceArr = ['Введите номер', 'Введите имя', 'чч:мм'];
//	
//	jAllInputElements.bind(
//		'focus',
//		function()
//		{
//		    for (var i in textToReplaceArr) 
//		    {
//                if (trim(this.value) == textToReplaceArr[i]) 
//    		    {
//                    this.value = "";
//    		    }     
//		    }
//		}
//	)
}

function checkFieldNotDefined(textValue) 
{
    textValue = trim(textValue);
    
    if (!textValue)
        return 1;
    
    for (var i in _pset.default_text_values)
    {
        if (_pset.default_text_values[i].toUpperCase() == textValue.toUpperCase())
        {
            //alert(_pset.default_text_values[i]);
            return 1;
        }
    }
    
    return 0;
}



function convert_date(date_str, time_str) {
	var ymd, hm = [0,0];
	ymd = date_str.split('.');
	hm = time_str.split(':');
	the_date = new Date(ymd[2], (ymd[1] - 1), ymd[0], hm[0], hm[1]);
	return the_date;
}


/**
* Terminator function
*/
function open_window_callme(val) 
{
    var vals_domain = {
    'com':'PduueiUL2vnNUNtDLVSsIw',
    'es':'PduueiUL2vnNUNtDLVSsIw', 
    'co.il':'i0lEc7_lRNyvXvr1MR_lfQ',
    'it':'PduueiUL2vnNUNtDLVSsIw',
    'ru':'PduueiUL2vnNUNtDLVSsIw',
    'cn':'PduueiUL2vnNUNtDLVSsIw'
    };
    
    if (typeof(val) == 'undefined')  
    {
        if (typeof(vals_domain[_pset.domain]) != 'undefined')
        {
            val = vals_domain[_pset.domain];
        }
        else
        val = 'PduueiUL2vnNUNtDLVSsIw';
        
        
    }
    
    callme_click(val);
    return false;
}

function open_window_callme_test() 
{
     var vals_domain = {
    'com':'SkGVxDL6WpVkyor0@On6dw',
    'es':'SkGVxDL6WpVkyor0@On6dw', 
    'co.il':'nYtbD8nXWt4UckjVc9vihQ',
    'it':'SkGVxDL6WpVkyor0@On6dw',
    'ru':'SkGVxDL6WpVkyor0@On6dw',
    'cn':'SkGVxDL6WpVkyor0@On6dw'
    };

    if (typeof(val) == 'undefined')  
    {
        if (typeof(vals_domain[_pset.domain]) != 'undefined')
        {
            val = vals_domain[_pset.domain];
        }
        else
        val = 'SkGVxDL6WpVkyor0@On6dw';
        
        
    }
    
    callme_click(val);
    return false;
}

function open_window_separate(url, name)
{
    if (typeof(name) == 'undefined') var name = 's_window';
    open_window(url, 900, 600, name);
}

function open_window_flash_phone(url, name)
{
    if (typeof(name) == 'undefined') var name = 'f_window';
    open_window(url, 280, 290, name);
}


function initHelpMessage(event, div_id)
{
    var position = {'width': 150, 'height': 100, 'left': 0, 'top': 0};
    initContextMessage(event, div_id, true, position);
}

function initMessageCallme(event, mTitle, mContent)
{
    var position = {'width': 355, 'height': 100, 'left': -8, 'top': -8};
    initMessage(event, mTitle, mContent, position);
    
//    var win = window.open('', 'name', 'fullscreen=no, toolbar=no, scrollbars=no, directories=no, status=no, menubar=yes, resizable=yes'); 
//    win.document.body.innerHTML = mContent;
//	win.focus();
}

function initMessage(event, mTitle, mContent, position, options)
{
    //var mClass = 'mScroll';
    var mClass = '';
    var str =
       
        '<table cols="3" cellspacing="0" cellpadding="0" class="cwAddonListMTable">'
       +'<tr>'
       +'   <td class="cwAddonListLTCorn"/>'
       +'   <td class="cwAddonListTop"/>'
       +'   <td class="cwAddonListRTCorn"/>'
       +'</tr>'
    
       +'<tr><td colspan="3">'
    
       +'<div class="cwALTitle">' + mTitle + '<br/>'
       +'    <div class="cwALTitleInterval">'
       +'          '
       +'    </div>'
       +'</div>'
        
       +'<div class="mInner ' + mClass + '">'
       +    mContent
       +'</div>'
        
       +'</td></tr>'
       +'<tr>'
       +    '<td class="cwAddonListLBCorn"/>'
       +    '<td class="cwAddonListBott"/>'
       +    '<td class="cwAddonListRBCorn"/>'
       +'</tr>'
       +'</table>'
       
    
    if (typeof(position) == 'undefined')
    {
        var position = {'width': 350, 'height': 240, 'left': -8, 'top': -8};
    }
    
    //alert(position.width)
    
    var bodrunnerPosition = getBodyPosition(event, position.width, position.height, position.left, position.top); 
    var options_default = 
    {
        id:         'mess',
        left:       bodrunnerPosition[0],
		top:        bodrunnerPosition[1],
        destall:    false,
        outclose:   true,
        have_select_tag: false,
        class_name: 'inline_window cwAddonListDiv'
    }
    
    if (typeof(options) != 'undefined' && sizeof(options))
    {
        for (var i in options)
        {
            options_default[i] = options[i];
        }
    }
    
    
    createPopupWindow(str, options_default);
}

function initMessage2(event, mTitle, mContent, position, options)
{
    //var mClass = 'mScroll';
    var mClass = '';
    var str =
       
        '<table cols="3" cellspacing="0" cellpadding="0" class="cwAddonListMTable2">'
       +'<tr>'
       +'   <td class="cwAddonListLTCorn"/>'
       +'   <td class="cwAddonListTop"/>'
       +'   <td class="cwAddonListRTCorn"/>'
       +'</tr>'
    
       +'<tr><td colspan="3">'
    
       +'<div class="cwALTitle">' + mTitle + '<br/>'
       +'    <div class="cwALTitleInterval">'
       +'          '
       +'    </div>'
       +'</div>'
        
       +'<div class="mInner ' + mClass + '">'
       +    mContent
       +'</div>'
        
       +'</td></tr>'
       +'<tr>'
       +    '<td class="cwAddonListLBCorn"/>'
       +    '<td class="cwAddonListBott"/>'
       +    '<td class="cwAddonListRBCorn"/>'
       +'</tr>'
       +'</table>'
       
    
    if (typeof(position) == 'undefined')
    {
        var position = {'width': 150, 'height': 340, 'left': -8, 'top': -8};
    }
    
    var bodrunnerPosition = getBodyPosition(event, position.width, position.height, position.left, position.top); 
    var options_default = 
    {
        id:         'mess',
        left:       bodrunnerPosition[0],
		top:        bodrunnerPosition[1],
        destall:    false,
        outclose:   true,
        have_select_tag: false,
        class_name: 'inline_window cwAddonListDiv'
    }
    
    if (typeof(options) != 'undefined' && sizeof(options))
    {
        for (var i in options)
        {
            options_default[i] = options[i];
        }
    }
    
    
    createPopupWindow(str, options_default);
}

function initMessagePhonesFormat(event, title, text_id)
{
    msg_txt = $('#'+text_id).html();

    initMessage(event, title, msg_txt);
    
}

    
function initCallmePhonesMessage(event, div_id, autoclose)
{
    var position = {'width': 390, 'height': 240, 'left': -398, 'top': -8};
    initContextMessage(event, div_id, autoclose, position);
}

function initContextMessage(event, div_id, autoclose, position)
{
    if (typeof(autoclose) == 'undefined')
        var autoclose = true;
        
    if (typeof(position) == 'undefined')
        var position = {'width': 352, 'height': 186, 'left': -8, 'top': -8};
        
        
    // var addonListDiv = $(document.createElement('div'));
    var addonListDiv = $('#' + div_id);
    
    // var bodrunnerPosition = getBodyPosition(event, 352, 186, -8, -8); // 352/184
    var bodrunnerPosition = [];
    
    cursorPosition = mousePageXY(event);
    
    var bodrunnerPosition = getBodyPosition(event, position.width, position.height, position.left, position.top); 
    
    $(addonListDiv)
        .css('left', bodrunnerPosition[0])
        .css('top', bodrunnerPosition[1])
        .css('position', 'absolute')
        .css('display', 'none');  

    if (autoclose)
    {
        $(addonListDiv).bind("mouseout", function(e){
            e = (e) ? e : ((window.event) ? event : null);
            var target = (e.relatedTarget) ? e.relatedTarget : 
                ((e.toElement) ? e.toElement : null);
                // alert(target)
            if(!isParent(target, addonListDiv[0])) {
                // cal_destroy_addList(addonListDiv);
                $(this).fadeOut();
            }
        });   
    }
  
  $('div.body').prepend(addonListDiv);
  
  $(addonListDiv).fadeIn();
}

/*********************************************************************/
/************************** block content ****************************/

function block_content() {
  var bc = document.getElementById('content_block_id');
  if((bc != null) && (typeof(bc)!="undefined") && (typeof(bc.parentNode) != "undefined") && (bc.parentNode != null)){
    bc.parentNode.removeChild(bc);
  }

  var cont_el = document.getElementById('content_all_id');
  var cont_el_q = $(cont_el);
  var position = cont_el_q.position();
  var offset = cont_el_q.offset();
  var w = cont_el_q.width();//var w = cont_el.offsetWidth;
  var h = cont_el_q.height();//var h = cont_el.offsetHeight;
  //var l = position.left + offset.left;
  var l = offset.left; 
  //var t = position.top + offset.top;
  var t = offset.top; 
  
  var msg_str1 = JSCoreLocale['loading'];
  var msg_str2 = ''; // 'Пожалуйста подождите';
  if((typeof(msg_str2) != "undefined") && (msg_str2 != ''))
	msg_str2 = '<br/>'+msg_str2;
  else
	msg_str2 = '';
  var cont_bl_msg_st = $('<div class="content_block_msgT">'+msg_str1+msg_str2+'</div>');
  var cont_bl_msg = $('<div class="content_block_msg"></div>')
       .append(cont_bl_msg_st);
  $(cont_bl_msg).css('left', ((w/2) - (185/2)))
       .css('top', ((h/2) - (40/2)));       

  var m = $('<div class="content_block" id="content_block_id"></div>');
  $(m).css('left', l)
       .css('top', t)
       .css('width', w)
       .css('height', h)
       .append(cont_bl_msg);
  
  $(document.body).append(m);
}

function unblock_content() {
  var bc = document.getElementById('content_block_id');
  if((typeof(bc)!="undefined") &&(typeof(bc.parentNode)!="undefined") && (bc.parentNode != null)){
    bc.parentNode.removeChild(bc);
  }
}

function block_all_content() {
	var msg_str1 = JSCoreLocale['waiting'];
	var msg_str2 = ''; // 'Пожалуйста подождите';
	if((typeof(msg_str2) != "undefined") && (msg_str2 != ''))
	msg_str2 = '<br/>'+msg_str2;
	else
	msg_str2 = '';
	var cont_bl_msg_st = $('<div class="content_block_msgT">'+msg_str1+msg_str2+'</div>');
	var cont_bl_msg = $('<div class="content_block_msg"></div>')
	     .append(cont_bl_msg_st);
	$.blockUI({ message: cont_bl_msg,
							css: { 
	  							width: '185px',
  								height: '40px',
  								top:  ($(window).height() - 40) /2 + 'px', 
                  left: ($(window).width() - 185) /2 + 'px', 
							    border: '0px'
							} 
					 });
}

function unblock_all_content() {
	$.unblockUI();
}
/************************** block content ****************************/
/*********************************************************************/

/** ***************************************************************** */
/* ************************** MESSAGE ******************************* */
$.blockAuthForm = function(msg) {
		if(typeof(msg) == 'undefined')
			var msg = '';
	
		var form_str = 
			'<div style="background-color: transparent;">'+
				'<form id="ajaxAuthForm" method="post" enctype="multipart/form-data" onsubmit="return false;">'+
				'<input type="hidden" name="action" value="auth"/>'+
				'<table cellspacing="0" cellpadding="0" style="width:100%;" class="blackForm">'+
				'<tr><td class="cornerWhiteTopLeft"> </td><td> </td><td class="cornerWhiteTopRight"> </td></tr>'+
				'<tr><td> </td><td>'+
					'<table cellspacing="0" cellpadding="0" style="width:100%;" class="blackFormInner">'+
						'<tr>'+
							'<td style="padding-bottom: 10px;">'+
								'<table cellspacing="0" cellpadding="0" style="width:100%;"><tr><td style="width:22px;"></td><td align="center" style="font-size:20px;">'+
							  	JSCoreLocale['auth_block']['title']+
						  	'</td><td style="width:22px;">'+
									'<img class="closeBtn_out" src="' + _pset.PATH_TO_IMG + '/blank.gif" title="'+JSCoreLocale['auth_block']['cancel']+'" alt="'+JSCoreLocale['auth_block']['cancel']+'" onclick="$.unblockUI();"'+
										'onmouseover="this.className=\'closeBtn_over\'" onmouseout="this.className=\'closeBtn_out\'"/>'+
								'</td></tr></table>'+
							'</td>'+
						'</tr>'+
						'<tr>'+
							'<td align="center" id="ajaxAuthFormErr" style="padding-bottom: 5px; font-size:12px; color:red;">'+msg+' </td>'+
						'</tr>'+
						'<tr>'+
							'<td align="center">'+
								JSCoreLocale['auth_block']['login']+
							'</td>'+
						'</tr>'+
						'<tr>'+
							'<td align="center" style="padding-bottom: 5px">'+
								'<input type="text" tabindex="1" name="txtUserName"/>'+
							'</td>'+
						'</tr>'+
						'<tr>'+
							'<td align="center">'+
								JSCoreLocale['auth_block']['passwd']+
							'</td>'+
						'</tr>'+
						'<tr>'+
							'<td align="center" style="padding-bottom: 5px">'+
								'<input type="password" tabindex="2" name="txtUserPass"/>'+
							'</td>'+
						'</tr>'+
						'<tr>'+
							'<td align="center" style="padding-top:10px;">'+
								'<input type="submit" id="ajaxAuthFormEnter" value="'+JSCoreLocale['auth_block']['enter']+'" style="width:150px;" onclick="sendAjaxAuthForm(); return false;"/>'+
								//'<input type="button" value="Отмена" style="width:80px;" onclick="$.unblockUI();"/>'+
							'</td>'+
						'</tr>'+
						'<tr>'+
							'<td style="padding-top:10px;" align="center">'+
//								'<table cellspacing="0" cellpadding="0" style="width:100%;"><tr><td style="width:22px;"></td><td align="center">'+
									'<a href="' + _pset.PATH_TO_ROOT_SCRIPT + '/registration_show" target="_blank" onclick="popupWin = '+
										'window.open(this.href, \'registration\', \'menubar, scrollbars, location\'); '+
										'popupWin.focus(); return false;">'+JSCoreLocale['auth_block']['register']+'</a>&nbsp;&nbsp;&nbsp;'+
									'<a href="' + _pset.PATH_TO_ROOT_SCRIPT + '/index/auth_form?param=pass_notification" target="_blank" onclick="popupWin = '+
										'window.open(this.href, \'pass_notification\', \'menubar, scrollbars, location\'); '+
										'popupWin.focus(); return false;">'+JSCoreLocale['auth_block']['forget']+'</a>'+
//								'</td><td style="width:22px;">'+
//									'<img class="closeBtn_out" src="' + _pset.PATH_TO_IMG + '/blank.gif" title="Отмена" alt="Отмена" onclick="$.unblockUI();"'+
//										'onmouseover="this.className=\'closeBtn_over\'" onmouseout="this.className=\'closeBtn_out\'"/>'+
//								'</td></tr></table>'+
							'</td>'+
						'</tr>'+
						'</tr>'+
					'</table>'+
				'</td><td> </td></tr>'+
				'<tr><td class="cornerWhiteBottomLeft"> </td><td> </td><td class="cornerWhiteBottomRight"> </td></tr>'+
				'</table>'+
				'</form>'+
			'</div>';
		var form_el = $(form_str);		
	  $.blockUI({ 
			message: form_el,
			css: {
		  	width:    '350px',
			border:   'none',
			opacity:  '1',
			backgroundColor: 'transparent'
	  	}
	  });	
}

function sendAjaxAuthForm() {
	
	
	var value = $('#ajaxAuthForm')[0];
	$('#ajaxAuthFormEnter')[0].disabled = true;
	
	//Create new JsHttpRequest object.
	var req = new JsHttpRequest();
  // Code automatically called on load finishing.
	//req.loader = 'xml';
	req.loader = $.browser.msie ? 'form' : 'xml';
    req.onreadystatechange = function() {
  	if (req.readyState == 4) {
  		if(req.status == 200) {
		  	if(req.responseJS.operation_status == 'ok') {
		  		$.unblockUI();
				}else
		  	if(req.responseJS.operation_status == 'no_auth') {
		  		$('#ajaxAuthFormErr')[0].innerHTML = JSCoreLocale['auth_errs']['no_auth'];
		  		$('#ajaxAuthFormEnter')[0].disabled = false;
	    		//alert('Ошибка: '+req.responseJS.errmsg);
		  	}else{
		  		$('#ajaxAuthFormErr')[0].innerHTML = 'undefined error';
		  		$('#ajaxAuthFormEnter')[0].disabled = false;
		  		//alert('Ошибка html:'+req.responseText);
				}
  		} else {
  			$('#ajaxAuthFormErr')[0].innerHTML = JSCoreLocale['click_err']['request']+' ('+req.status+').<br/>'+JSCoreLocale['click_err']['request2'];
	  		$('#ajaxAuthFormEnter')[0].disabled = false;
  		}
	  }
  }
  //var objToSend = { q: value };
  var objToSend = {
  		  'action': value.action.value,
  			'txtUserName': value.txtUserName.value,
  			'txtUserPass': value.txtUserPass.value
  		};
  
  req.open(null , _pset.PATH_TO_ROOT + '/backend.php', true);
  req.send( objToSend );
}

function submitFormByAjax(action, jq_form, options) 
{
	
    requestByAjax(action, jq_form.formToArraySubmittable(), options);
}

function requestByAjax(action, data, options) {
    var req = new JsHttpRequest();
  // Code automatically called on load finishing.
	
	var oToSend = { 'action': action };
    oToSend = mergeObjects(oToSend, data);
	
	//req.loader = 'xml';
	req.loader = $.browser.msie ? 'form' : 'xml';
    req.onreadystatechange = function() 
    {
      	if (req.readyState == 4) 
      	{
      		if(req.status == 200) 
      		{
      		  if(req.responseJS.operation_status == 'no_auth') 
      		  {
                 $.blockAuthForm(JSCoreLocale['auth_errs']['not']);
        		 //alert('Ошибка: '+req.responseJS.errmsg);
    		  } 
    		  else if(req.responseJS.operation_status == 'ok') 
    		  {
    		  	 //$.unblockUI();
    		  	 document.location.href = req.responseJS.ret_url;
    		  	 return;
    		  }
    		  
    		  if(typeof(options.onSuccess) == 'function')
    		  {
      			options.onSuccess(req.responseJS, req.responseText);
    		  }
      		  else
      		  {
                 $.blockClickMSG(
    	  	 			JSCoreLocale['click_err']['request'], 
    	  				JSCoreLocale['click_err']['undef'],
    	  				'cancel');
      		  }
      		} 
      		else 
      		{
      			$.blockClickMSG(
    	  				JSCoreLocale['click_err']['title'], 
    	  				JSCoreLocale['click_err']['request']+' ('+req.status+').<br/>'+JSCoreLocale['click_err']['request2'],
    	  				'cancel');
      		}
      		if(typeof(options.call_back_funct) == 'function')
      		{
      			options.call_back_funct();
      		}
    	}
    }
 
    req.open(null , _pset.PATH_TO_ROOT + '/backend.php', true);
    req.send( oToSend );
}

$.blockClickMSG = function(title, message, type) {
	var title_el_str = '';
	var message_el_str = '';	
	var typeclass = '';
	switch(type){
		case 'tips':
			typeclass = 'growlUITips';
			break;
		case 'info':
			typeclass = 'growlUIInfo';
			break;
		case 'alert':
			typeclass = 'growlUIAlert';
			break;
		case 'help':
			typeclass = 'growlUIHelp';
			break;
		case 'cancel':
			typeclass = 'growlUICancel';
			break;
		default:
			typeclass = 'growlUI';
	}

	if (title) title_el_str = '<h1>'+title+'</h1>';
	if (message) message_el_str = '<h2>'+message+'</h2>';
	var mes_str = '<table class="growlUITable" cellspacing="0" cellpadding="0" style="width:100%;"><tr><td class="'+typeclass+'">'+
				   '<div class="growlUIImgCont"><img class="'+typeclass+'_img" src="' + _pset.PATH_TO_IMG + '/blank.gif"/></div>'+
				    title_el_str+message_el_str+
				  '</td></tr></table>';
	var mes = $(mes_str);		
  $.blockUI({ 
		message: mes,
		css: {
	  	width:    '350px',
		  border:   'none',
		  padding:  '5px',
		  opacity:  '0.6',
	      color:    '#fff',
		  backgroundColor: '#000',
		  '-webkit-border-radius': '10px',
		  '-moz-border-radius':    '10px'
  	}
  });	
  $('.blockOverlay').attr('title',JSCoreLocale['continue']).click($.unblockUI);
  mes.attr('title',JSCoreLocale['continue']).click($.unblockUI);
}

$.growlUISPmb = function(title, message, type, typeclass, timeout) {
	var title_el_str = '';
	var message_el_str = '';
	if (title) title_el_str = '<h1>'+title+'</h1>';
	if (message) message_el_str = '<h2>'+message+'</h2>';
	var mes_str = '<table class="growlUITable" cellspacing="0" cellpadding="0"><tr><td class="'+typeclass+'">'+
				   '<div class="growlUIImgCont"><img class="'+typeclass+'_img" src="' + _pset.PATH_TO_IMG + '/blank.gif"/></div>'+
				    title_el_str+message_el_str+
				  '</td></tr></table>';
	var mes = $(mes_str);		
	if (timeout == undefined) timeout = 3000;
    $.blockUI({ 
		message: mes,
		fadeIn: 700, fadeOut: 1000, centerY: false,
		timeout: timeout, showOverlay: false,
		css: /*
					 * { width: '350px', top: '10px', left: '', right: '10px', border:
					 * 'none', padding: '5px', backgroundColor: '#000',
					 * '-webkit-border-radius': '10px', '-moz-border-radius': '10px',
					 * opacity: '.6', color: '#fff' }
					 */
		$.blockUI.defaults.growlCSS
    }, type);	
};
// spec msg
$.showMsgBT = function(title, message, sptype, type, timeout){
	// sptype - id msg
	var typeclass = '';
	switch(type){
		case 'tips':
			if (timeout == undefined) timeout = 3000;
			typeclass = 'growlUITips';
			break;
		case 'info':
			if (timeout == undefined) timeout = 3000;
			typeclass = 'growlUIInfo';
			break;
		case 'alert':
			if (timeout == undefined) timeout = 3000;
			typeclass = 'growlUIAlert';
			break;
		case 'help':
			if (timeout == undefined) timeout = 3000;
			typeclass = 'growlUIHelp';
			break;
		case 'cancel':
			if (timeout == undefined) timeout = 3000;
			typeclass = 'growlUICancel';
			break;
		default:
			if (timeout == undefined) timeout = 3000;
			typeclass = 'growlUI';
	}
	$.growlUISPmb(title, message, sptype, typeclass, timeout);
}

$.echo = function (text_msg, time)
{
    if (typeof(time) == 'undefined') var time = 5000;
    $.showMsgBT('Notify!', text_msg, 'notify' + Math.random(1000), 'info', time);
}

var globalCurMouseXY = null;
$.showMsgBTBeforeDelay = function(title, message, sptype, type, elem, delay, timeout){
  if (delay == undefined) delay = 500;
  if((typeof(document.onmousemove) === 'undefined') || (document.onmousemove == null)){
    document.onmousemove = function(e){globalCurMouseXY = mousePageXY(e);};	
  }
  var p = $(elem);
  var position = p.offset();//p.position();
  var w = elem.offsetWidth;
  var h = elem.offsetHeight;
  l = position.left;
  t = position.top;  
  setTimeout("$.showMsgBTBeforeDelayCheckXY('"+title+"','"+message+"','"+sptype+"','"+type+"',"+w+","+h+","+t+","+l+",'"+timeout+"');", delay);
}

$.showMsgBTBeforeDelayCheckXY = function(title, message, sptype, type, width, height, top, left, timeout){
	var mouseXY = globalCurMouseXY;
	if(mouseXY != null)
	if((mouseXY.x >= left) && (mouseXY.x <= (left + width)) && (mouseXY.y >= top) && (mouseXY.y <= (top + height))){
		$.showMsgBT(title, message, sptype, type, timeout);
	}
}

function calChangeMsgStat(elem) {
  var msgStatOff = $.cookie("cookMsgStat");
  if(msgStatOff == 1){
    calMsgStatOff = 0;
    $.cookie("cookMsgStat", null);
    elem.className = 'calMsgOn';
    elem.onmouseover = function(){this.className='calMsgOnAct';showMsg(this,'msg_off');};
    elem.onmouseout = function(){this.className='calMsgOn';};
  }else{
    calMsgStatOff = 1;
    $.cookie("cookMsgStat", "1", {expires: 7});
    elem.className = 'calMsgOff';
    elem.onmouseover = function(){this.className='calMsgOffAct';};
    elem.onmouseout = function(){this.className='calMsgOff';};
  }
}

function calOnLoadMsgCh(elem) {
  var msgStatOff = $.cookie("cookMsgStat");
  if(msgStatOff == 1){
    calMsgStatOff = 1;
    elem.className = 'calMsgOff';
    elem.onmouseover = function(){this.className='calMsgOffAct';};
    elem.onmouseout = function(){this.className='calMsgOff';};
  }else{
    calMsgStatOff = 0;
  }  
}

var msgStatOff = 0; 
function changeMsgStat(elem) {
  if($.cookie("msgStat") == 1){
    msgStatOff = 0;
    $.cookie("msgStat", null);
    elem.className = 'calMsgOn';
    elem.onmouseover = function(){this.className='calMsgOnAct';showMsgAboutMsgCh(this);};
    elem.onmouseout = function(){this.className='calMsgOn';};
  }else{
    msgStatOff = 1;
    $.cookie("msgStat", "1", {expires: 7});
    elem.className = 'calMsgOff';
    elem.onmouseover = function(){this.className='calMsgOffAct';};
    elem.onmouseout = function(){this.className='calMsgOff';};
  }
}

function onLoadMsgCh(elem) {
  if($.cookie("msgStat") == 1){
    msgStatOff = 1;
    elem.className = 'calMsgOff';
    elem.onmouseover = function(){this.className='calMsgOffAct';};
    elem.onmouseout = function(){this.className='calMsgOff';};
  }else{
    msgStatOff = 0;
  }  
}

function showMsgAboutMsgCh(elem, type){
  if(msgStatOff != 1)
  	$.showMsgBTBeforeDelay(JSCoreLocale['change_state']['title'], JSCoreLocale['change_state']['on_off'],'cal_msg_offon','info',elem,700,2000); 
}

/****************/

/*
 function JT_init(){
         $("a.jTip")
       .hover(function(){JT_show(this.href,this,this.name)},function(){$('#JT').remove()})
           .click(function(){return false});     
}
 */

function JT_show(elem,title,bodyhtml,width,height){
  if(title == false)title="&nbsp;";
  
	if(typeof(width) == 'undefined'){var width = 250};
	if(typeof(height) == 'undefined'){var height = 0};

	var coord_elem = getBounds(elem);
	
  var de = document.documentElement;
  //var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
  //var h = self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
  var w = $(window).width();
  var h = $(window).height();
  var sl = $(window).scrollLeft();
  var st = $(window).scrollTop();
  var hasArea = w - coord_elem.left + sl; //getAbsoluteLeft(elem);
  var hasAreaH = h - coord_elem.top + st;  
  var clickElementy = coord_elem.top - 3; //getAbsoluteTop(elem) - 3; //set y position

  var bodyHtml = '';
	var titleHtml = '';
	var cellHtml = '';
	var ua = navigator.userAgent.toLowerCase();
	
	
  if((height <= 0) || (hasAreaH > (height*1))) { // msg up->down
	  if ((hasArea > ((width*1) + coord_elem.width)) && (_pset.LANGUAGE!='he'))
	   { // msg right
			titleHtml+= '<tr><td id="JT_arrow_top" rowspan="2"><img id="JT_arrow_left" src="' + _pset.PATH_TO_IMG + '/blank.gif"/></td>' +
			            '    <td id="JT_title">'+title+'</td>' +
									'</tr>'; 
			cellHtml+= '<tr><td id="JT_copy">'+bodyhtml+'</td></tr>';
			var zzzz = titleHtml + cellHtml;
			
	    var arrowOffset = coord_elem.width;// + 11; //getElementWidth(elem) + 11;
	    var clickElementx = coord_elem.left + arrowOffset; //getAbsoluteLeft(elem) + arrowOffset; //set x position
	  }else{ // msg left
			if (_pset.LANGUAGE == 'he')
			{
	      
	           titleHtml+= '<tr><td id="JT_arrow_top" rowspan="2"><img id="JT_arrow_right" src="'+_pset.PATH_TO_IMG+'/blank.gif"/></td><td id="JT_title">'+title+'</td>' +

			            '</tr>';
			} else
			{
			      titleHtml+= '<tr><td id="JT_title">'+title+'</td>' +
			            '    <td id="JT_arrow_top" rowspan="2"><img id="JT_arrow_right" src="'+_pset.PATH_TO_IMG+'/blank.gif"/></td>';
			            '</tr>';
			}
		  cellHtml+= '<tr><td id="JT_copy">'+bodyhtml+'</td></tr>';
		  var zzzz = titleHtml + cellHtml;
		  
	    var clickElementx = coord_elem.left - ((width*1));// + 15);//getAbsoluteLeft(elem) - ((width*1) + 15); //set x position
	  }
  } else { // msg down->up
  	if((hasArea > ((width*1) + coord_elem.width)) && (_pset.LANGUAGE!='he')) { // msg right 
  		
			titleHtml+= '<tr><td id="JT_arrow_bott"><img id="JT_arrow_left" src="'+_pset.PATH_TO_IMG+'/blank.gif"/></td>' +
			            '    <td id="JT_title">'+title+'</td>' +
									'</tr>'; 
			cellHtml+= '<tr><td id="JT_arrow_bott_fix"></td><td id="JT_copy">'+bodyhtml+'</td></tr>';
			var zzzz = cellHtml + titleHtml;
			
	    var arrowOffset = coord_elem.width;// + 11; //getElementWidth(elem) + 11;
	    var clickElementx = coord_elem.left + arrowOffset; //getAbsoluteLeft(elem) + arrowOffset; //set x position
	  }else{ // msg left
			if (_pset.LANGUAGE == 'he')
			{
	           titleHtml+= '<tr><td id="JT_arrow_bott"><img id="JT_arrow_right" src="'+_pset.PATH_TO_IMG+'/blank.gif"/></td><td id="JT_title">'+title+'</td>' +
			       
			            '</tr>';
			             cellHtml+= '<tr><td id="JT_arrow_bott_fix"></td><td id="JT_copy">'+bodyhtml+'</td></tr>';
			} else
			{
			      titleHtml+= '<tr><td id="JT_title">'+title+'</td>' +
			            '    <td id="JT_arrow_bott"><img id="JT_arrow_right" src="'+_pset.PATH_TO_IMG+'/blank.gif"/></td>';
			            '</tr>';
			             cellHtml+= '<tr><td id="JT_copy">'+bodyhtml+'</td><td id="JT_arrow_bott_fix"></td></tr>';
			}
		 // cellHtml+= '<tr><td id="JT_copy">'+bodyhtml+'</td><td id="JT_arrow_bott_fix"></td></tr>';
		  var zzzz = cellHtml + titleHtml;
		  
	    var clickElementx = coord_elem.left - (width*1);// + 15);//getAbsoluteLeft(elem) - ((width*1) + 15); //set x position
	  }  	
  	clickElementy = coord_elem.top - (height*1);
  }
  
  zzzz = '<table id="JT_table" cellspacing="0" cellpadding="0" style="width:'+width*1+'px;">'+ zzzz + '</table>';
  var is6IE = (ua.indexOf("6.0") != -1);  
  if (is6IE && $('select').length)
		zzzz = '<iframe scrolling="no" frameborder="0" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; filter:alpha(opacity=0)"></iframe>' + zzzz;    
  bodyHtml+= '<div id="JT">'+ zzzz +'</div>';		
  $("body").append(bodyHtml);//left side
   
  $('#JT').css({left: clickElementx+"px", top: clickElementy+"px"});
  //$('#JT_copy').html(bodyhtml);
	$('#JT').show();
}

function getElementWidth(elem) {
  //x = document.getElementById(objectId);
  //x = objectId;
  return elem.offsetWidth;
}

function blockEvents(evt) {
              if(evt.target){
              evt.preventDefault();
              }else{
              evt.returnValue = false;
              }
}

/****************/

function simpleMessage(event, mTitle, mContent, width, height)
{
  if (typeof(width) == 'undefined')
  	var width = 350;
  
  if (typeof(height) == 'undefined')
  	var height = 240;
	
	var mClass = '';
	var str =
	    '<table cols="3" cellspacing="0" cellpadding="0" class="smMTable" style="width:'+width+'px;">'
	   +'<COLGROUP><COL class="smCol"/><COL/><COL class="smCol"/></COLGROUP>'
	   +'<tr>'
	   +'   <td class="smLTCorn">'
	   +'			<img class="smCorn" src="' + _pset.PATH_TO_IMG + '/blank.gif"/>'
	   +'		</td>'	
	   +'   <td class="smTop">'
	   +'			<img src="' + _pset.PATH_TO_IMG + '/blank.gif"/>'
	   +'		</td>'		   
	   +'   <td class="smRTCorn">'
	   +'			<img class="smCorn" src="' + _pset.PATH_TO_IMG + '/blank.gif"/>'
	   +'		</td>'		   
	   +'</tr>'
	
	   +'<tr><td colspan="3">'
	
	   +'<div class="smTitle">' + mTitle + '<br/>'
	   +'    <div class="cwALTitleInterval">'
	   +'          '
	   +'    </div>'
	   +'</div>'
	    
	   +'<div class="smInner ' + mClass + '">'
	   +    mContent
	   +'</div>'
	    
	   +'</td></tr>'
	   +'<tr>'
	   +'   <td class="smLBCorn">'
	   +'			<img class="smCorn" src="' + _pset.PATH_TO_IMG + '/blank.gif"/>'
	   +'		</td>'	
	   +'   <td class="smBottom">'
	   +'			<img src="' + _pset.PATH_TO_IMG + '/blank.gif"/>'
	   +'		</td>'		   
	   +'   <td class="smRBCorn">'
	   +'			<img class="smCorn" src="' + _pset.PATH_TO_IMG + '/blank.gif"/>'
	   +'		</td>'
	   +'</tr>'
	   +'</table>';
    
    var bodrunnerPosition = getBodyPosition(event, width, height, -8, -8); 
    var options = 
    {
        id:         'simpleMess',
        left:       bodrunnerPosition[0],
        top:        bodrunnerPosition[1],
        destall:    false,
        outclose:   true,
        have_select_tag: true,
        class_name: 'smBase'
    }

    createPopupWindow(str, options);
}
/* ************************** MESSAGE ******************************* */
/** ***************************************************************** */

/**********************************************************************/
/*************************** popup window *****************************/
function checkExAnyPopupWindows() {
	if(_pset.popupWinArr.length < 1)
		return false;
	for(var i = 0; i < _pset.popupWinArr.length; i++) {
		if(_pset.popupWinArr[i].value != 0)
			return true;
	}
	return false;
}

function checkExPopupWindows(id) {
	if(_pset.popupWinArr.length < 1)
		return false;
	for(var i = 0; i < _pset.popupWinArr.length; i++) {
		if(_pset.popupWinArr[i].id == id)
			return true;
	}
	return false;
}

function setStatPopupWindows(id, stat) {
//	if(_pset.popupWinArr.length < 1)
//		return false;
	for(var i = 0; i < _pset.popupWinArr.length; i++) {
		if(_pset.popupWinArr[i].id == id){
			_pset.popupWinArr[i].value = stat;
			return true;
		}
	}
	addStatPopupWindows(id, stat);
	return false;
}

function addStatPopupWindows(id, stat) {
//	if(_pset.popupWinArr.length < 1)
//		return false;
	var i = _pset.popupWinArr.length;
	_pset.popupWinArr[i] = {
  	'id': id,
  	'value': stat
  };
	return true;
}

/*
 * options:
 *  - fadeout: true (smooth collapse) / false (remove without fadeout) - def
 *  - exceptions: array id elements that don't remove in mass remove 
 *  - massmode: true (remove all by id prefix) / false (remove all by status in global array)  - def
 * 
 * if el exist, then exceptions and massmode don't use.
 */
function destroyPopupWindow(options, el) {
	if(typeof(el) == 'undefined' || el == null){ // mass remove
		if(typeof(options.massmode) != 'undefined' && options.massmode == true) { // remove all by id prefix
		  if(typeof(options.exceptions) != 'undefined')
			  var exceptFlag = true;
			else
			  var exceptFlag = false;
			var divmenu_arr = $('div[id^=popupWin_]');
	    for(var i=0; i < divmenu_arr.length; i++){
				if(exceptFlag == true) {
					var el_id = divmenu_arr[i].getAttribute('id');
					if(el_id.lenght > 9){
						if(in_array(el_id.substring(9), options.exceptions) == true)
						  continue;
					}
				}
	      destroyPopupWindow(options, divmenu_arr[i]);
	    }
		}else{ // remove all by status in global array
		  if(checkExAnyPopupWindows() == true){
				if(typeof(options.exceptions) != 'undefined')
	        var exceptFlag = true;
	      else
	        var exceptFlag = false;
	      for(var i=0; i < _pset.popupWinArr.length; i++) {
					if(_pset.popupWinArr[i].value == 0)
					  continue;
					if (exceptFlag == true) 
						if(_pset.popupWinArr[i].id.lenght > 9)
	            if(in_array(_pset.popupWinArr[i].id.substring(9), options.exceptions) == true)
	              continue;
				  var elem = document.getElementById(_pset.popupWinArr[i].id);
					if(typeof(elem) != 'object' || elem == null)
					  continue;
	        destroyPopupWindow(options, elem);
	      }
	    }
		}
	}else{ // remove only selected element
	  if(typeof(el) != 'object')
		  el = document.getElementById(el);
		if(el == null)
		  return 0;
		var el_id = el.getAttribute('id');
		var cont_el_id = el.getAttribute('cont_el_id');
		if(cont_el_id != null && cont_el_id != ''){
			var cont_el_elem = document.getElementById(cont_el_id);
			//if(typeof(cont_el_elem) == "object") {
			if(cont_el_elem != null) {
				var oldClass = el.getAttribute('oldClass');
			  if(oldClass != null)
			  	cont_el_elem.className = oldClass;
			  else
			  	cont_el_elem.className = '';
			}
		}
	  el.onmouseout = function(){};
	  if(typeof(options.fadeout) != 'undefined' && options.fadeout == true) {
		  $(el).fadeOut("fast", function(){
		      if((typeof(this.parentNode)!='undefined') && (this.parentNode != null)){
		        this.parentNode.removeChild(this);
		      }
		    });
	  }else{
	  	if((typeof(el.parentNode)!='undefined') && (el.parentNode != null)){
        el.parentNode.removeChild(el);
      }
	  }
	  if(el_id){
	  	if(checkExPopupWindows(el_id) == true)
	  		setStatPopupWindows(el_id, 0);
	  	else
	  		addStatPopupWindows(el_id, 0);
	  }
	}
}

/*
 * options:
 *  - id
 *  - left
 *  - top
 *  - destall: true - def / false (optional)
 *  - outclose: true / false
 *  - class_name (optional)
 *  - cont_el_id (optional)
 *  - old_class  (optional)
 *  - have_select_tag (fix select in IE6, optional) 
 *  - select_hide (hide select, optional) 
 */
function createPopupWindow(elem_innerHTML, options) {
	if( typeof(elem_innerHTML) == 'undefined' || elem_innerHTML == ''
	 || typeof(options.id)   == 'undefined' || options.id == ''
	 || typeof(options.left) == 'undefined' || options.left == ''
	 || typeof(options.top)  == 'undefined' || options.top == '' )
	  return 0;
	var id = 'popupWin_' + options.id;
	
	if(typeof(options.call_back_funct) == 'function')
	{
	    var ofadeout = false;
	}
	else
	{
	    var ofadeout = true;
	}
	 
	//destroyPopupWindow({'fadeout': false}, id);
	if((typeof(options.destall) != 'undefined') && (options.destall == false))
		destroyPopupWindow({'fadeout': ofadeout}, id);
	else
		destroyPopupWindow({'fadeout': ofadeout});
	setStatPopupWindows(id, 1);
  //cal_menuNodeOper = 1;

    var popupWindow_div = document.createElement('div');
    if(typeof(options.class_name) != 'undefined')
      popupWindow_div.className = options.class_name;
		
  //popupWindow_div.className = 'calCreateEvDiv';
    $(popupWindow_div).attr('id', id).
      css('left', options.left).
      css('top', options.top).
      css('display', 'none');
		
	if(typeof(options.cont_el_id) != 'undefined') 
	  $(popupWindow_div).attr('cont_el_id', options.cont_el_id);
	if(typeof(options.old_class) != 'undefined')
	  $(popupWindow_div).attr('oldClass', options.old_class);

    if(typeof(options.outclose) == 'undefined' || options.outclose == true) {
	  $(popupWindow_div).bind("mouseout", function(e){
          //return true;
	      e = (e) ? e : ((window.event) ? event : null);
	      var target = (e.relatedTarget) ? e.relatedTarget : 
	          ((e.toElement) ? e.toElement : null);

	      //if(!isParent(target, popupWindow_div)) {
          if(jQuery.inArray($(popupWindow_div)[0], $(target).parents()) == -1) {
	        //cal_destroy_nodemenu(true, node_menu_div);
	        
            destroyPopupWindow({'fadeout': ofadeout}, popupWindow_div);
	      }
	  });
	} 

  if (typeof(options.have_select_tag) != 'undefined' && options.have_select_tag && $.browser.msie )
	{
	    var ua = navigator.userAgent.toLowerCase();
      var is6IE = (ua.indexOf("6.0") != -1);
      if (is6IE && $('select').length)
      {
      	if (typeof(options.select_hide) != 'undefined')
        {
          $('select').hide();    
        }else{
        	elem_innerHTML = 
        		'<iframe scrolling="no" frameborder="0" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; filter:alpha(opacity=0)"></iframe>'
        		+ elem_innerHTML;
        }      	
//            if (typeof(options.have_select_tag_win) != 'undefined')
//            {
//                $('select').hide();    
//            }
//            else
//            {
//                elem_innerHTML = 
//                    '<iframe scrolling="no" frameborder="0" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; filter:alpha(opacity=0)"></iframe>'
//                    + elem_innerHTML;    
//            }
      }
	}
	
	popupWindow_div.innerHTML = elem_innerHTML;
	
	document.body.appendChild(popupWindow_div);
	
  if(typeof(options.call_back_funct) == 'function')
  {
    options.call_back_funct();
  }
  
	$(popupWindow_div).fadeIn("fast", function(){
    $(this).css('display', '');
	}); 
}



/*************************** popup window *****************************/
/**********************************************************************/

/**********************************************************************/
/******************** special Form with paginator *********************/
_pset.spForm = new Array();

/*
 * change page
 */
function spChPage(formid, operation, param1) {
	if( typeof(formid) == 'undefined' || typeof(operation) == 'undefined'
		 || typeof(_pset.spForm[formid]) == 'undefined'
		 || formid == '' || operation == ''
		 || (operation != 'next' && operation != 'prev' && operation != 'first' && operation != 'last' && operation != 'goto' && operation != 'changespp' && operation != 'curr')
		 || (operation == 'goto' && (typeof(param1) == 'undefined' || param1 == ''))
		 || (operation == 'changespp' && (typeof(param1) == 'undefined' || param1 == '')))
			return 0;

	if(typeof(_pset.spForm[formid].readOnly) == 'undefined')
		_pset.spForm[formid].readOnly = 'true';
		
	if(_pset.spForm[formid].readOnly == 'false') 
		if(!(operation == 'curr' && (typeof(param1) != 'undefined' && param1 == true))) {
			if(spCheckPage(formid) == false) {
				// need add error msg
				alert('spCheckPage');
				return 0;
			}
		}
	
	if(operation == 'changespp') {
		_pset.spForm[formid].strPerPage = param1;
		_pset.spForm[formid].currPage = 1;
		operation = 'first';
	}
	
	var countStr = _pset.spForm[formid].length;
//	alert('countStr:'+countStr);
//	alert('formid:'+formid);
//	alert("1");
	if(countStr > 0) {
		//alert("2");
		var currPage = _pset.spForm[formid].currPage;
		//strForEdit
		var strPerPage = _pset.spForm[formid].strPerPage;
		var paginatorDelta = _pset.spForm[formid].paginatorDelta;
		var restOfLastPage = countStr%strPerPage;
		var countPages = Math.ceil(countStr/strPerPage);
		//alert('strPerPage:'+strPerPage+'; currPage:'+currPage+'; restOfLastPage:'+restOfLastPage+'; countPages:'+countPages);
    switch (operation) {
      case 'first':
        currPage = 1;
        break;
      case 'last':
			  //if(currPage == countPages)
        //  return 0;
        currPage = countPages;
        break;      
			case 'goto':
			  currPage = 1;
			  break;  
    }

		if(currPage > countPages || currPage < 1 || strPerPage < 1 || paginatorDelta < 1)
			return 0;	
	
		switch(operation) {
			case 'prev':
				if((currPage - (paginatorDelta + 1)) < 1)
					return 0;
				currPage -= (paginatorDelta + 1);
				break;
			case 'next':
				if((currPage + (paginatorDelta + 1)) > countPages)
					return 0;
				currPage += (paginatorDelta + 1);
				break;
			case 'first':
				//if(currPage == 1)
				//	return 0;
				currPage = 1;
				break;
			case 'last':
				//if(currPage == countPages)
				//	return 0;
				currPage = countPages;
				break;
			case 'goto':
				var gotoPageNumber = parseInt(param1);
				if(gotoPageNumber < 1 || gotoPageNumber > countPages)// || gotoPageNumber == currPage)
					return 0;
				currPage = gotoPageNumber;
				break;
			case 'curr':
			  break;
		}
	
	  var first_el = (currPage-1)*strPerPage + 1;
	  if(currPage == countPages && restOfLastPage != 0)
	    var last_el = first_el + (restOfLastPage - 1);
	  else
	  	var last_el = first_el + (strPerPage - 1);
	}else{
		var currPage = 1;
		var countPages = 0;
		var first_el = 1;
		var last_el = 0;
	}
  
	if(_pset.spForm[formid].readOnly == 'false')
		spCreateTable(formid, first_el, last_el);
	else
		spCreateTableRO(formid, first_el, last_el);
  
  _pset.spForm[formid].currPage = currPage;
//  if(countPages > 1)
  if(_pset.spForm[formid].readOnly == 'false')
  	spCreatePanel(formid);
  
  spCreatePG(formid, currPage, countPages, strPerPage, paginatorDelta);
//  if(countStr > 0)
  spCreateSPP(formid, strPerPage, countStr);
  
  if (formid == 'infPhoneDetForm')
		hideSMSfields();

}

/*
 * validate current page and set new values
 */
function spCheckPage(formid) {
  var arrPhDet = $("#"+formid+" tr.spTR");
  var countCurrStr = arrPhDet.length;
  var fields = _pset.spForm[formid].fields;
  
  if(countCurrStr == 0) {
  	//alert('countCurrStr:'+countCurrStr);
  	return true;
  }//else
  	//alert('countCurrStr:'+countCurrStr);
  	
	
  // check all field by validator
  //...
  
  // set new values
  
  // calculate numbers first and last form-elements in _pset.spForm[formid][x]
  var countStr = _pset.spForm[formid].length;

	if(countStr < 1)
		return true;
		
  if(typeof(_pset.spForm[formid].strToDel)=='undefined')
	  var strToDel = 0;
	else
	  var strToDel = _pset.spForm[formid].strToDel;
		
	//alert("2");
	var currPage = _pset.spForm[formid].currPage;
	//strForEdit
	var strPerPage = _pset.spForm[formid].strPerPage;
	var paginatorDelta = _pset.spForm[formid].paginatorDelta;
	var restOfLastPage = countStr%strPerPage;
	var countPages = Math.ceil(countStr/strPerPage);
	if(strToDel != 0 && restOfLastPage == 0 && (Math.ceil((countStr+1)/strPerPage))==currPage) {
		_pset.spForm[formid].strToDel = 0;
		_pset.spForm[formid].currPage--;
		return true;
	}
	//alert('strToDel:'+strToDel+'; restOfLastPage:'+restOfLastPage);
	
	//alert('strPerPage:'+strPerPage+'; currPage:'+currPage+'; restOfLastPage:'+restOfLastPage+'; countPages:'+countPages);
	if(currPage > countPages || currPage < 1 || strPerPage < 1 || paginatorDelta < 1)
		return false;	

	var first_el = (currPage-1)*strPerPage + 1;
/*  if(currPage == countPages && restOfLastPage != 0)
    var last_el = first_el + (restOfLastPage - 1);
  else
  	var last_el = first_el + (strPerPage - 1);*/
  
	var delcounter = 0;

	//var spvalue = '';
	var rc_check;	
  for(var i=0; i < countCurrStr; i++) {
  	//var xxx='';
  	if((first_el + i) == strToDel) {
			_pset.spForm[formid].strToDel = 0;
			delcounter++;
			continue;
		}
  	for(var key in fields) {
  		var el = $(arrPhDet[i]).find('[name="'+key+'"]');
  		var msg = fields[key].msg;
  		var value = el[0].value;
  		rc_check = spCheckValByType(fields[key].type, value);
  		if(typeof(rc_check) != 'object') {
  			alert('check page error!');
  			return 0;
  		}
  		if(msg == rc_check.val)
  			rc_check.val = '';
  		_pset.spForm[formid][(first_el + i - delcounter)][key] = rc_check;

  		/*if(msg == value)
  			_pset.spForm[formid][(first_el + i - delcounter)][key].val = '';
  		else {
  			_pset.spForm[formid][(first_el + i - delcounter)][key].val = value;
  		}*/

  		
  		//xxx+='key:'+key+' value:'+el[0].value+';';
		}
  	//alert(xxx);
  }
  
  return true;
}

/*
 * generate form table HTML and add to form
 */
function spCreateTable(formid, first_el, last_el) {
	var fields = _pset.spForm[formid].fields;
	var countStr = _pset.spForm[formid].length; 
	var countFields = 0;
	for(var key in fields) {
  	countFields++;	    
	}
	if(countFields == 0){
		alert('fields dont set!');
		return 0;
	}		
	
	// title
	var titleHTML = '<tr>';// class="bg_grow">';

	titleHTML += '<th width="7px" class="first"><img height="24px" width="7px" border="0" src="'+_pset.PATH_TO_IMG+'/blank.gif"/></th>';
	titleHTML += '<th width="30px"></th>';
	
	for (var key in fields) {
  	titleHTML += '<th width="' + fields[key]['width'] + '"><div id="'+fields[key]['id']+'" class="spInner">' + fields[key]['desc'] + '</div></th>';
  }
	titleHTML += '<th class="last_t"></th>';
	titleHTML += '<th width="25px" class="last_t"></th>';
	titleHTML += '<th width="7px" class="last"><img height="24px" width="7px" border="0" src="'+_pset.PATH_TO_IMG+'/blank.gif"/></th>';
	titleHTML += '</tr>';

	// bottom
	var bottomHTML = '<tr class="">';
	bottomHTML += '<td class="first_b"></td>';
	bottomHTML += '<td class="bottom"></td>';
	for(var key in fields) {
  	bottomHTML += '<td class="bottom"></td>';	 
	}
	bottomHTML += '<td class="bottom_t"></td>';
	bottomHTML += '<td class="bottom_t"></td>';
	bottomHTML += '<td class="last_b"></td>';
	bottomHTML += '</tr>';
	
	// body
	var bodyHTML = '';
	var inputHTML = '';
	var align = '';
	var style = '';
	var styleflag = 0;
	var strCounter = 1;
	var styleCell = '';
	for(var i=first_el; i <= last_el; i++) {
		styleflag = strCounter%2;
		styleCell = '';
		if(styleflag == 0)
			styleCell = ' spBGgrow';
		bodyHTML += '<tr class="spTR'+styleCell+'">';
		bodyHTML += '<td class="first"></td>';
		bodyHTML += '<td align="right"><div class="spInner">'+i+'</div></td>';
		//spBGgrow
		for(var key in fields) {
			bodyHTML += spGetCellHTML(formid, key, i, styleflag);
		}
		
		bodyHTML += '<td class="last_t"></td>';
		bodyHTML += '<td align="center" class="last_t"><a tabindex="-1" alt="'+JSLocaleCore['phone_list']['delete_num']+'" title="'+JSLocaleCore['phone_list']['delete_num']+'" onclick="spDeleteRow(\''+formid+'\', this, '+ i +'); return false;" href="#"><img class="icon_element" src="' + _pset.PATH_TO_IMG + '/element_delete.png"/></a></td>'
		
		bodyHTML += '<td class="last"></td>';
		bodyHTML += '</tr>';
		strCounter++;
	}
	
	var tableHTML = '<table width="100%" cellspacing="0" cellpadding="0" class="spTblContent">';
	tableHTML += titleHTML;
	tableHTML += bodyHTML;
	tableHTML += bottomHTML;
	tableHTML += '</table>';
	
	//var form = $("#"+formid)[0];
	$("#"+formid).html(tableHTML);
	//form.innerHTML = tableHTML;
}

/*
 * generate form table (read only) HTML and add to form
 */
function spCreateTableRO(formid, first_el, last_el) {
	var fields = _pset.spForm[formid].fields;
	var countStr = _pset.spForm[formid].length; 
	var countFields = 0;
	for(var key in fields) {
  	countFields++;	    
	}
	if(countFields == 0){
		alert('fields dont set!');
		return 0;
	}		
	
	// title
	var titleHTML = '<tr>';// class="bg_grow">';

	titleHTML += '<th width="7px" class="first"><img height="24px" width="7px" border="0" src="'+_pset.PATH_TO_IMG+'/blank.gif"/></th>';
	titleHTML += '<th width="30px"></th>';
	
	var width = '';
	for (var key in fields) {
		if(typeof(fields[key]['width']) != 'undefined' && (fields[key]['width']*1) > 0)
			width = ' style="width:'+fields[key]['width']+'px;"';
		else
			width = '';
  	titleHTML += '<th'+width+'><div class="spInner">' + fields[key]['desc'] + '</div></th>';
  }
	titleHTML += '<th class="last_t"></th>';
	titleHTML += '<th width="7px" class="last"><img height="24px" width="7px" border="0" src="'+_pset.PATH_TO_IMG+'/blank.gif"/></th>';
	titleHTML += '</tr>';

	// bottom
	var bottomHTML = '<tr class="">';
	bottomHTML += '<td class="first_b"></td>';
	bottomHTML += '<td class="bottom"></td>';
	for(var key in fields) {
  	bottomHTML += '<td class="bottom"></td>';	 
	}
	bottomHTML += '<td class="bottom_t"></td>';
	bottomHTML += '<td class="last_b"></td>';
	bottomHTML += '</tr>';
	
	// body
	var bodyHTML = '';
	var inputHTML = '';
	var align = '';
	var style = '';
	var styleflag = 0;
	var strCounter = 1;
	var styleCell = '';
	for(var i=first_el; i <= last_el; i++) {
		styleflag = strCounter%2;
		styleCell = '';
		if(styleflag == 0)
			styleCell = ' spBGgrow';
		bodyHTML += '<tr class="spTR'+styleCell+'">';
		bodyHTML += '<td class="first"></td>';
		bodyHTML += '<td align="right"><div class="spInner">'+i+'</div></td>';
		//spBGgrow
		for(var key in fields) {
			bodyHTML += spGetCellROHTML(formid, key, i, styleflag);
		}
		
		bodyHTML += '<td class="last_t"></td>';
		bodyHTML += '<td class="last"></td>';
		bodyHTML += '</tr>';
		strCounter++;
	}
	
	var tableHTML = '<table width="100%" cellspacing="0" cellpadding="0" class="spTblContent">';
	tableHTML += titleHTML;
	tableHTML += bodyHTML;
	tableHTML += bottomHTML;
	tableHTML += '</table>';
	
	//var form = $("#"+formid)[0];
	$("#"+formid).html(tableHTML);
	//form.innerHTML = tableHTML;
}

/*
 * generate Cell (read only) HTML by type
 */
function spGetCellROHTML(formid, field, number) {
	var fields = _pset.spForm[formid].fields;
	var bodyHTML = '';
	var value = '';
	var msg = '';
	var align = 'left';

	if(typeof(fields[field].msg) != 'undefined')
		msg = fields[field].msg;
	if(typeof(fields[field].align) != 'undefined')
		align = fields[field].align;

	if(typeof(_pset.spForm[formid][number][field].val) == 'undefined' || _pset.spForm[formid][number][field].val == null || _pset.spForm[formid][number][field].val == '')
		value = msg;
	else
		value = _pset.spForm[formid][number][field].val;

    if (fields[field].type == 'sms_text')
        bodyHTML += '<td align="'+align+'" valign="middle"><div class="spInner"><input type="text" value="'+value+'" width="'+fields[field].width+'"readonly="true"/></div></td>';
    else
	   bodyHTML += '<td align="'+align+'" valign="middle"><div class="spInner"><span title="'+value+'">'+value+'</span></div></td>';

	return bodyHTML;	
}

/*
 * generate Cell HTML by type
 */
function spGetCellHTML(formid, field, number) {
	var fields = _pset.spForm[formid].fields;
	var type = fields[field].type;
	var width = fields[field].width;
	var padding = 8;
	//alert('type:'+type);
	
	var bodyHTML = '';
	var formElHTML = '';
//	var err = '';
	//var newel = '';
	var value = '';
	var msg = '';
	var style= '';
	var mouseoverout = '';
	if(typeof(fields[field].msg) != 'undefined')
		msg = fields[field].msg;
/*	var width = '';
	if(typeof(fields[field].width) != 'undefined')
		if(parseInt(fields[field].width) > padding)
			width = ' width="'+(parseInt(fields[field].width) - padding)+'px"';*/

	switch(type) {
		case 'phonenumber':

			var dopclass = '';
			if(typeof(_pset.spForm[formid][number][field].err) != 'undefined' && _pset.spForm[formid][number][field].err == 1) {
				dopclass = ' class="errorInside"';

	      mouseoverout = ' onmouseover="spFormMsg(\''+formid+'\',this)" onmouseout="$(\'#JT\').remove()"';

			}

			if(typeof(_pset.spForm[formid][number][field].val) == 'undefined' || _pset.spForm[formid][number][field].val == null || _pset.spForm[formid][number][field].val == '') {
				value = msg;
				if(dopclass == '')
					dopclass = ' class="form_help_text"';
				else
					dopclass = dopclass.slice(0,-1) + ' form_help_text"';
			}else{
				value = _pset.spForm[formid][number][field].val;
			}
			var margin = ' margin:2px 0px 1px 2px;';
			if($.browser.msie) {
				width = width - 28;
				margin = ' margin:2px 0px 1px 0px;';
			} else
				width = width - 26;
			style = ' style="width:'+width+'px; float:left; margin:0;"';
			formElHTML = '<input'+dopclass+style+' type="text"' + 
									 ' name="'+field+'" id="input_user_phone_'+number+'" value="'+value+'"' +
									 ' onblur="spCheckFormEl(\''+formid+'\', this); checkEmptyOut(this, \''+msg+'\');" onfocus="checkEmptyIn(this, \''+msg+'\')"' +
									 mouseoverout + '/>';
									 //' size="14"/>';
			formElHTML+= '<img border="0" style="cursor: pointer;'+margin+'" title="'+JSLocaleCore['phone_list']['select_num']+'" onclick="add_from_book(event, '+number+'); return false;" href="#" src="' + _pset.PATH_TO_IMG +'/frombook.gif"/>';
									 //' size="14"'+err+newel+'/>';
			bodyHTML += '<td valign="middle"><div class="spInner">'+formElHTML+'</div></td>';

			break;
		
		
		case 'sms_text':
				
			var dopclass = '';

			if((typeof(_pset.spForm[formid][number][field])!='undefined') && typeof(_pset.spForm[formid][number][field].err) != 'undefined' && _pset.spForm[formid][number][field].err == 1) { 
				dopclass = ' class="errorInside"';
	      mouseoverout = ' onmouseover="spFormMsg(\''+formid+'\',this)" onmouseout="$(\'#JT\').remove()"';
			}
			//errorInside			
			if((typeof(_pset.spForm[formid][number][field]) =='undefined') || typeof(_pset.spForm[formid][number][field].val) == 'undefined' ) {
				value = '';
				
			}else{
				value = _pset.spForm[formid][number][field].val;
			}
			var margin = ' margin:2px 0px 1px 2px;';
			if($.browser.msie) {
				width = width - 28;
				margin = ' margin:2px 0px 1px 0px;';
			} else
				width = width - 26;
			style = ' style="width:'+width+'px; margin:0;"';
			formElHTML = '<input'+dopclass+style+' type="text"' + 
									 ' name="'+field+'" id="input_user_txtmsg_'+number+'" onblur="spCheckFormEl(\''+formid+'\', this);" '+mouseoverout+' value="'+value.replace(/\"/g,'&quot;')+'"' + '/>';
								
			bodyHTML += '<td id="sms_text" valign="middle"><div class="spInner">'+formElHTML+'</div></td>';
		
			break;
			
		case 'other...':
			break;
	}
	
	return bodyHTML;
}

/*
 * generate Panel HTML and add to form
 */		
function spCreatePanel(formid) {
	var countStr = _pset.spForm[formid].length;
	var maxCountStr = _pset.spForm[formid].maxCountStr;
	var bodyHTML = '<table cellspacing="0" cellpadding="0" class="spTblPanel"><tr>';
	
	if(countStr < maxCountStr) {
	
		bodyHTML += '<td width="84px"><div style="padding:0 7px 0 0;"><a href="#" onclick="spAddRow(\''+formid+'\'); return false;"><table cellspacing="0" cellpadding="0" title="'+JSLocaleCore['phone_list']['insert_num']+'" style="cursor: pointer;"><tr>';

		bodyHTML += '<td class="spPanAddImg"></td><td class="spPanTxt">'+JSLocaleCore['phone_list']['insert']+'</td>';
		bodyHTML += '</tr></table></a></div></td>';
		
		bodyHTML += '<td width="140px"><div style="padding:0 7px 0 0;"><a href="#" onclick="spShowDialogOpenFile(\''+formid+'\', event); return false;"><table cellspacing="0" cellpadding="0" title="'+JSLocaleCore['phone_list']['add_from_file']+'" style="cursor: pointer;"><tr>';
		bodyHTML += '<td class="spPanAddFileImg"></td><td class="spPanTxt">'+JSLocaleCore['phone_list']['add2']+'</td>';
		bodyHTML += '</tr></table></a></div></td>';
	}
	
	if(countStr > 0) {
		bodyHTML += '<td width="124px"><div style="padding:0 7px 0 0;"><a href="#" onclick="spDeleteAllRows(\''+formid+'\'); return false;"><table cellspacing="0" cellpadding="0" title="'+JSLocaleCore['phone_list']['clear_phone']+'" style="cursor: pointer;"><tr>';
		bodyHTML += '<td class="spPanDelAllImg"></td><td class="spPanTxt">'+JSLocaleCore['phone_list']['clear_list']+'</td>';
		bodyHTML += '</tr></table></a></div></td>';
	}
	
/*	var classMsg, onMouseOver, onMouseOut;
	if($.cookie("msgStat") == 1){
    msgStatOff = 1;
    classMsg = 'calMsgOff';
    onMouseOver = 'calMsgOffAct';
    onMouseOut = 'calMsgOff';
	}else{
    msgStatOff = 0;
    classMsg = 'calMsgOn';
    onMouseOver = 'calMsgOnAct';
    onMouseOut = 'calMsgOn';
  }  
	
	bodyHTML += '<td>&nbsp;</td>';
	bodyHTML += '<td align="right" style="width: 26px;">';
	bodyHTML += '<img class="'+classMsg+'" height="21" width="24" onmousedown="changeMsgStat(this);" alt="msgOffOn" onload="onLoadMsgCh(this);"'+
    					' src="' + _pset.PATH_TO_IMG + '/blank.gif" title="" onmouseover="this.className=\''+onMouseOver+'\';showMsgAboutMsgCh(this);" onmouseout="this.className=\''+onMouseOut+'\'"/></td>';
*/	bodyHTML += '<td>&nbsp;</td>';
	
	bodyHTML += '<td width="70px" title="'+JSLocaleCore['phone_list']['phones_count']+'" style="color:#AAAAAA;">[ <b>'+countStr+'</b> / <b>'+maxCountStr+'</b> ]</td>';
	
	bodyHTML += '</tr></table>';
	$("#"+formid+"PANEL").html(bodyHTML);
}

/*
*
*/
function hideSMSfields()
{
	$('#sms_text_title').hide();
	$('input[id^="input_user_txtmsg_"]').hide();
	
	if ($('form input[id="type_sms"]').attr("checked"))
	{
		$('#sms_text_title').show();
		$('input[id^="input_user_txtmsg_"]').show();
	}
}

/*
 * generate SPPChanger HTML and add to form
 */
function spCreateSPP(formid, strPerPage, countStr) {
	if(countStr < 1) {
		$("#"+formid+"SPP").html('');
		return true;
	}
		
	var sppNewHTML = '';
	sppNewHTML += '<span style="color:#AAAAAA;">'+JSLocaleCore['phone_list']['show_by']+'&nbsp;&nbsp;</span>';
	var arrSPP = new Array(5,10,20,50,100);
	var countArrSPP = arrSPP.length;
	for(var j=0; j < countArrSPP; j++) {
		if(strPerPage == arrSPP[j])
			sppNewHTML += '<span class="spSPPSelected">'+ arrSPP[j] +'</span>';
		else
			sppNewHTML += '<span class="spSPPOther" onclick="spChangeSPP(\''+formid+'\','+arrSPP[j]+')">'+ arrSPP[j] +'</span>';
		if(countArrSPP != (j+1)) {
			sppNewHTML += '&nbsp;';
			sppNewHTML += '|';
			sppNewHTML += '&nbsp;';
		}
	}
	sppNewHTML += '&nbsp;<span style="color:#AAAAAA;">'+JSLocaleCore['phone_list']['rows_per_page']+'</span>';
	
	$("#"+formid+"SPP").html(sppNewHTML);
}

/*
 * generate paginator HTML and add to form
 */
function spCreatePG(formid, currPage, countPages, strPerPage, paginatorDelta) {
	if(countPages < 1) {
		$("#"+formid+"PG").html('');
		return true;
	}
	var pgNewHTML = '<div class="spPagDiv"><ul><li class="spInfo">'+JSLocaleCore['phone_list']['pages']+'</li>';
  var title = '';
	if (currPage > (paginatorDelta + 1)) {
		title = JSLocaleCore['rows']['title']+' '+JSLocaleCore['rows']['from']+' ' + 1 + ' '+JSLocaleCore['rows']['to']+' ' + strPerPage;
  	pgNewHTML += '<li class="spPOP"><a title="'+title+'" href="#" onclick="spChPage(\'' + formid + '\',\'first\'); return false;">1</a></li>';
  }
	if (currPage > (paginatorDelta + 2)) {
		title = JSLocaleCore['rows']['title']+' '+JSLocaleCore['rows']['from']+' ' + ((currPage - (paginatorDelta + 2)) * strPerPage + 1) + ' '+JSLocaleCore['rows']['to']+' ' + ((currPage - (paginatorDelta + 1)) * strPerPage);
  	pgNewHTML += '<li class="spPOP"><a title="'+title+'" href="#" onclick="spChPage(\'' + formid + '\',\'prev\'); return false;">...</a></li>';
  }

	pgNewHTML += spGetPGpagelist('dec', currPage, countPages, strPerPage, formid, paginatorDelta);
	
	pgNewHTML += '<li class="spPCP"><a href="#" onclick="return false;">'+currPage+'</a></li>';
	
	pgNewHTML += spGetPGpagelist('inc', currPage, countPages, strPerPage, formid, paginatorDelta);
	
	if ((countPages - currPage) > (paginatorDelta + 1)) {
		title = JSLocaleCore['rows']['title']+' '+JSLocaleCore['rows']['from']+' ' + ((currPage + (paginatorDelta)) * strPerPage + 1) + ' '+JSLocaleCore['rows']['to']+' ' + ((currPage + (paginatorDelta + 1)) * strPerPage);
  	pgNewHTML += '<li class="spPOP"><a title="'+title+'" href="#" onclick="spChPage(\'' + formid + '\',\'next\'); return false;">...</a></li>';
  }
	if ((countPages - currPage) > paginatorDelta) {
    title = JSLocaleCore['rows']['title']+' '+JSLocaleCore['rows']['from']+' ' + (strPerPage*(countPages-1)+1) + ' '+JSLocaleCore['rows']['to']+' ' + (strPerPage*countPages);		
  	pgNewHTML += '<li class="spPOP"><a title="'+title+'" href="#" onclick="spChPage(\'' + formid + '\',\'last\'); return false;">' + countPages + '</a></li>';
  }
	
	pgNewHTML += '</ul></div>';
	
	$("#"+formid+"PG").html(pgNewHTML);
}

/*
 * need for spCreatePG
 */
function spGetPGpagelist(direction, currpage, countpage, strPerPage, formid, n) {
	var html = '';
	
	switch(direction) {
		case 'inc':
			for (var i = 1; (i <= n && ((currpage + i) <= countpage)); i++) {
				title = JSLocaleCore['rows']['title']+' '+JSLocaleCore['rows']['from']+' ' + ((currpage + i - 1)*strPerPage + 1) + ' '+JSLocaleCore['rows']['to']+' ' + ((currpage + i)*strPerPage);
	  	  html += '<li class="spPOP"><a title="'+title+'" href="#" onclick="spChPage(\'' + formid + '\',\'goto\',' + (currpage + i) + '); return false;">' + (currpage + i) + '</a></li>';
	    }
			break;
		case 'dec':
			for(var i=n; i > 0; i--) {
				if ((currpage - i) > 0) {
					title = JSLocaleCore['rows']['title']+' '+JSLocaleCore['rows']['from']+' ' + ((currpage - i - 1)*strPerPage + 1) + ' '+JSLocaleCore['rows']['to']+' ' + ((currpage - i)*strPerPage);
			    html += '<li class="spPOP"><a title="'+title+'" href="#" onclick="spChPage(\'' + formid + '\',\'goto\',' + (currpage - i) + '); return false;">' + (currpage - i) + '</a></li>';
		    }
			}
			break;
	}
	return html;
}

/*
 * change "string per page"
 */
function spChangeSPP(formid, value) {
	spChPage(formid, 'changespp', value);

}

/*
 * delete selected row
 */
function spDeleteRow(formid, el, i) {
	var countStr = _pset.spForm[formid].length;
	if(i > countStr)
	  return 0;
	
	_pset.spForm[formid].strToDel = i;
	for(var j=i; j < countStr; j++) {
		_pset.spForm[formid][j] = _pset.spForm[formid][j+1];
	}
	delete _pset.spForm[formid][countStr];
	_pset.spForm[formid].length--;

	spChPage(formid, 'curr');

}

/*
 * delete all rows
 */
function spDeleteAllRows(formid) {
	var countStr = _pset.spForm[formid].length;
	if(countStr < 1)
		return 0;
	
	for(var j = countStr; j >= 1; j--) {
		delete _pset.spForm[formid][j];
	}
	_pset.spForm[formid].length = 0;
	
	var ignore_check = true;
	spChPage(formid, 'curr', ignore_check);
}

/*
 * add new row
 */
function spAddRow(formid) {
	var countStr = _pset.spForm[formid].length;
	var maxCountStr = _pset.spForm[formid].maxCountStr;
	if(countStr >= maxCountStr)
		return 0;
	var fields = _pset.spForm[formid].fields;
//	var type = fields[field].type;
	_pset.spForm[formid][(countStr+1)] = new Object;
	_pset.spForm[formid][(countStr+1)].id = 0;

//	var fields = _pset.spForm[formid].fields;
	//var type = fields[field].type;	
	//spCheckValByType(type, value)
	var type;
	var value = '';
	var rc_check;
	for(var key in fields) {
		value = '';
		//alert('fields[key].type:'+fields[key].type+'; value:'+value);
		rc_check = spCheckValByType(fields[key].type, value);
		if(typeof(rc_check) != 'object') {
			alert('add row error');
			return 0;
		}
		_pset.spForm[formid][(countStr+1)][key] = rc_check; //{'val': ''};
	}
	
	_pset.spForm[formid].length++;
	
	spChPage(formid, 'last');

}

/*
 * add list rows
 */
function spAddManyRows(formid, arr) {
	var countStr = parseInt(_pset.spForm[formid].length);
	var maxCountStr = _pset.spForm[formid].maxCountStr;
	var countRows = parseInt(arr.length);
	_pset.filedata = arr;
	
	if(countStr >= maxCountStr || (countStr + countRows) > maxCountStr)
		return 0;
	
	for(var i=1; i <= countRows; i++)
		_pset.spForm[formid][(countStr+i)] = arr[i];
	
	_pset.spForm[formid].length+=countRows;	
	
	spChPage(formid, 'last');
	
} 

/*
 * show dialog "insert from file" 
 */
function spShowDialogOpenFile(formid, event) { 
	var countStr = _pset.spForm[formid].length;
	var maxCountStr = _pset.spForm[formid].maxCountStr;
	if(countStr >= maxCountStr) {
		// вывести сообщение о лимите
		return 0;	
	}
	var difference = maxCountStr - countStr;
	
	var bodrunnerPosition = getBodyPosition(event, 350, 155, -14, -47);
	
	//title
  var title_str = JSLocaleCore['phone_list']['add_file'];
  title_str = '<div class="infOpenFileTitle">'+title_str+'</div>';
  var onclickOk_str = 'spSendFile(\''+formid+'\');';
	var buttonOk_str = JSLocaleCore['phone_list']['load'];
  var onclickCancel_str = 'destroyPopupWindow({\'fadeout\': true}, \'popupWin_infOpenFile\');';

  var body_str = '<tr><td style="padding:3px;">'+
        '<table cellspacing="0" cellpadding="0" style="margin:0px 0px 4px 0px;padding:0px 0px 4px 0px;width:100%;height:100%;border:0px;">'+
/*        '<tr>'+
        	'<td rowspan="2" style="padding: 0 3px 0 0;"><img class="stepImg1_32" src="'+_pset.PATH_TO_IMG+'/blank.gif"/></td>'+
          '<td><span style="color:#446688;font-size:13px;">Выберите разделитель между колонками в загружаемом файле:</span></td></tr>'+
        '<tr><td align="right"><select name="separator">'+
          '	<option value="1">Пробел ( )</option>'+ //space
          '	<option value="2" selected="selected">Символ табуляции</option>'+ //tab
          '	<option value="3">Запятая (,)</option>'+ //comma
          '	<option value="4">Точка с запятой (;)</option>'+ //semicolon
          '</select></td></tr>'+*/
        '<tr>'+
//        	'<td rowspan="2" style="padding: 3px 3px 0 0;"><img class="stepImg2_32" src="'+_pset.PATH_TO_IMG+'/blank.gif"/></td>'+
        	'<td style="padding: 3px 0 0 0;"><span style="color:#446688;font-size:13px;">'+JSLocaleCore['phone_list']['choose_txt']+'</span></td></tr>'+
        '<tr><td align="right"><input type="file" name="userfile"/></td></tr>'+
//        '<tr><td colspan="2" style="padding:3px 0 0 0;color:green;font-size:13px;">Из файла возможно загрузить не более <span style="color:#333333; font-weight: bold;" title="В список обзвона уже добавлено '+countStr+' из '+maxCountStr+' возможных">'+difference+'</span> телефонных номеров</td></tr>'+
        '<tr><td style="padding:3px 0 0 0;color:green;font-size:13px;">'+JSLocaleCore['phone_list']['load_no_more']+'<span style="color:#333333; font-weight: bold;" title="'+JSLocaleCore['phone_list']['load_no_more']+countStr+' '+JSLocaleCore['phone_list']['out_of']+maxCountStr+JSLocaleCore['phone_list']['possible']+'">'+difference+'</span> '+JSLocaleCore['phone_list']['phone_num']+'</td></tr>'+
        '<tr><td style="padding: 3px 0 0 0;"><span style="color:green;font-size:13px;">'+JSLocaleCore['phone_list']['choose_txt_note']+'</span></td></tr>'+        
        '</table></td></tr>'+
    '<tr><td align="center">'+ 
         '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;width:100%;height:100%;border:0px;"><tr>'+
         '<td class="infOpenFileBtnOk" onmouseout="this.className=\'infOpenFileBtnOk\'" onmouseover="this.className=\'infOpenFilBtnOkOver\'" onclick="'+onclickOk_str+'">'+buttonOk_str+'</td>'+
         '<td class="infOpenFileBtnCancel" onmouseout="this.className=\'infOpenFileBtnCancel\'" onmouseover="this.className=\'infOpenFileBtnCancelOver\'" onclick="'+onclickCancel_str+'">'+JSLocaleCore['phone_list']['cancel']+'</td></tr></table></td></tr>';

	body_str = '<form method="post" enctype="multipart/form-data" onsubmit="return false" style="border:0px;" id="'+formid+'OFForm">'+
		'<input type="hidden" name="separator" value="2"/>'+ /////////// !!!!!!!!!!!!!!!!!!!!! separator
		'<input type="hidden" name="MAX_FILE_SIZE" value="1000000"/>'+
		'<input type="hidden" name="maxcountrecords" value="'+difference+'"/>'+
		'<table class="infOpenFileBodyTable" cellspacing="0" cellpadding="0">' + body_str + '</table></form>';                  
	
	// aggregation
	var mtable_str = '<table class="infOpenFileMTable" cellspacing="0" cellpadding="0" cols="3">' +
	'  <tr><td class="infOpenFileLTCorn"></td><td class="infOpenFileTop"></td><td class="infOpenFileRTCorn"></td></tr>' +
	'  <tr><td colspan="3">'+title_str+body_str+'</td></tr>' +
	'  <tr><td class="infOpenFileLBCorn"></td><td class="infOpenFileBott"></td><td class="infOpenFileRBCorn"></td></tr>' +
	'</table>';

	createPopupWindow(mtable_str, {
		'id': 'infOpenFile',
		'left': bodrunnerPosition[0],
		'top': bodrunnerPosition[1],
		'class_name': 'infOpenFileDiv',
		'outclose': false
	});  	

}

/*
 * send file contained phone list by ajax 
 */
function spSendFile(formid) {
	var value = document.getElementById(formid+'OFForm');
	
	if(value.userfile.value == '') {
		$.blockClickMSG(JSLocaleCore['phone_list']['please'],	"",	'alert');
		return 0;
	}
		
	var fields = _pset.spForm[formid].fields;
	var countFields = 0;
	for(var key in fields) {
  	countFields++;	    
	}
	if(countFields == 0) {
		alert('fields dont set!');
		return 0;
	}		
	
	// проверить поля	

	
	block_all_content();
	var preReq = new JsHttpRequest();
	//preReq.loader = 'xml';
	preReq.loader = $.browser.msie ? 'form' : 'xml';
	preReq.onreadystatechange = function() {
		if (preReq.readyState == 4) {
  		if(preReq.status == 200) {
		  	if(preReq.responseJS.operation_status == 'ok') {
		  		// begin --= Send File =--
		  		
		  		//Create new JsHttpRequest object.
		  		var  req = new JsHttpRequest();
		  	  // Code automatically called on load finishing.
		  	  req.onreadystatechange = function() {
		  		  if (req.readyState == 4) {
		  		  	destroyPopupWindow({'fadeout': true});
		  		  	if((req.responseJS.flag != null) && (req.responseJS.flag == 1)){
		  		  		spAddManyRows(formid, req.responseJS.data);
		  		  		unblock_all_content();
		  				}else
		  		  	if((req.responseJS.flag != null) && (req.responseJS.flag == 2)){
		  		  		unblock_all_content();
		  		  		$.blockClickMSG(JSLocaleCore['check_file']['title'],	JSLocaleCore['check_file']['format'], 'cancel');
		  		  	}else{
		  		  		unblock_all_content();
		  		  		$.blockClickMSG(JSLocaleCore['check_file']['title'],	JSLocaleCore['check_file']['send'], 'cancel');
		  				}
		  		  	
		  		  }
		  	  }
		  	 
		  	  var objToSend = {'action': 'informer_main',
		  				 				 'operation': 'load_file',
		  				 				 q: value };
		  		
		  		for(var key in fields)
		  			objToSend['fields['+key+']'] = fields[key]['type'];
		  	  
		  	  req.open(null , _pset.PATH_TO_ROOT + '/backend.php', true);
		  	  req.send( objToSend );
		  	  
		  		// end --= Send File =--
				}else
		  	if(preReq.responseJS.operation_status == 'no_auth') {
		  		unblock_all_content();
		  		$.blockAuthForm(JSLocaleCore['auth_errors']['not']);
	    		//alert('Ошибка: '+preReq.responseJS.errmsg);
		  	}else{
		  		unblock_all_content();
		  		$.blockClickMSG(
		  				JSLocaleCore['click_err']['title'], 
		  				JSLocaleCore['click_err']['undef'],
		  				'cancel');
		  		//alert('Ошибка html:'+preReq.responseText);
				}
  		} else {
  			unblock_all_content();
  			$.blockClickMSG(
	  				JSLocaleCore['click_err']['title'], 
	  				JSLocaleCore['click_err']['request']+' ('+preReq.status+').<br/>'+JSLocaleCore['click_err']['request2'],
	  				'cancel');
  		}
	  }
  }
	preReq.open(null , _pset.PATH_TO_ROOT + '/backend.php', true);
	preReq.send( {'action': 'auth_test'} );
}

function spErrMsg(formid, elem) {
  if(msgStatOff != 1) {
  	var fields = _pset.spForm[formid].fields;
  	var title = '';
  	var msg = '';
  	var timeout = 4000;
  	if(typeof(fields[elem.name].errtitle) != 'undefined')
  		title = fields[elem.name].errtitle;
  	if(typeof(fields[elem.name].errmsg) != 'undefined')
  		msg = fields[elem.name].errmsg;
  	if(typeof(fields[elem.name].timeout) != 'undefined')
  		timeout = fields[elem.name].timeout;
  	//alert(msg);
//	    case 'past':
//	      $.showMsgBT('Прошедшее время', 'Создание событий в прошлом не имеет смысла!','cal_past','alert',3000);
    $.showMsgBTBeforeDelay(title, msg,'sp_err_msg','info',elem,700,timeout);
  }
}

/******************** special Form with paginator *********************/
/**********************************************************************/

/*********************************************************************/
/**************************** Validation *****************************/
_pset.spDataTypes = {
	'phonenumber': {
		'type': 'str',
		'reg_exp': /^[0-9]{5,20}[\.\,0-9]{0,12}$/
	},
	'sms_text': {
		'type': 'str',
		'permit_null': 1,
		'range_high': 255
	}
	
};

/*
var fields = _pset.spForm[formid].fields;
  		rc_check = spCheckValByType(fields[key].type, value);
 */

function spCheckFormEl(formid, elem) {
	var fields = _pset.spForm[formid].fields;
	var type = fields[elem.name].type;

	var rc_check = spCheckValByType(type, elem.value);
	if(typeof(rc_check) != 'object') {
		alert('check value error');
		return 0;
	}
	
//mouseoverout = ' onmouseover="spFormMsg(\''+formid+'\',this)" onmouseout="$(\'#JT\').remove()"';	
	
	if(rc_check.err == 1) {
		//elem.style.cssText = 'border: 1px dotted red;';
		$(elem).addClass('errorInside');
		elem.onmouseover = function() {spFormMsg(formid,this)};
		elem.onmouseout = function() {$('#JT').remove()};
		//elem.onmouseover = function() {spErrMsg(formid, this);};
		
		//style = ' style="border: 1px dotted red;"';
		//mouseover = ' onmouseover="spErrMsg(\''+formid+'\', this);"';
	}else{
		//elem.style.cssText = '';
		$(elem).removeClass('errorInside');
		elem.onmouseover = function() {};
		elem.onmouseout = function() {};
		$('#JT').remove();
	}
		
	/*if(typeof(_pset.spForm[formid][number][field].err) != 'undefined' && _pset.spForm[formid][number][field].err == 1) {
		style = ' style="border: 1px dotted red;"';
		mouseover = ' onmouseover="spErrMsg(\''+formid+'\', this);"';
	}*/
	
	//spErrMsg(formid, elem);
}

function spCheckValByType(type, value) {
	if(typeof(_pset.spDataTypes[type]) != 'object'){
		alert('wrong field type!');
		return 0;
	}
	var sptype = '';
	var options = {};
	for(var key in _pset.spDataTypes[type]) {
		if(key == 'type')
			sptype = _pset.spDataTypes[type][key];
		else
			options[key] = _pset.spDataTypes[type][key];
	}

	return spValidation(value, sptype, options);
}

/* options:
 * - reg_exp      | exemple: '/^[0-9]+$/' 
 *                        or '/^[0-9\.\,]+$/'
 *                        or '/^[0-2][0-9]:[0-9]{2}$/'
 *                        ...
 * - range_low    | inclusive, value >= range_low
 *                  format for date/datetime/datetimes in date_type=2
 * - range_high   | inclusive, value <= range_high
 *                  format for date/datetime/datetimes in date_type=2
 * - date_type    | 1 - yyyy-mm-dd / 2 - dd.mm.yyyy (must be exist for date/datetime/datetimes)
 * - permit_null  | 1 - true
 * - def_val      | if (value == null) then value = def_val
 * - allowed_vals | if value in allowed_vals array => ok
 * 
 * type: 
 * - int 
 * - float
 * - str
 * - time         | hh:mm
 * - times        | hh:mm:ss
 * - date         | date
 * - datetime     | date hh:mm
 * - datetimes    | date hh:mm:ss
 */
function spValidation(value, type, options) {
	
	
	if(typeof(value) != 'undefined'){
		if(value == null)
			value = '';
		else
			value = trim(value+'');
	}else
	  value = '';
  var optRegExpExist = false;
  var optRangeLowExist = false; 
  var optRangeHighExist = false; 
  var optDateTypeExist = false;
  var optPermitNullExist = false;
  var optDefValExist = false;
  var optAllowValsExist = false;  
  if((typeof(options) == 'object') && (count(options) > 0)){
    if(typeof(options['reg_exp']) != 'undefined' && (options['reg_exp'] != null))
      optRegExpExist = true;
    if(typeof(options['range_low']) != 'undefined' && (options['range_low'] != null))
      optRangeLowExist = true;
    if(typeof(options['range_high']) != 'undefined' && (options['range_high'] != null))
      optRangeHighExist = true;
    if(typeof(options['date_type']) != 'undefined' && (options['date_type'] != null) 
        && (/^[1-2]$/.test(options['date_type']+'')))
      optDateTypeExist = true;
    if(typeof(options['permit_null']) != 'undefined' && (options['permit_null'] != null))
      optPermitNullExist = true; 
    if(typeof(options['def_val']) != 'undefined' && (options['def_val'] != null))
      optDefValExist = true;
    if(typeof(options['allowed_vals']) != 'undefined' && sizeof(options['allowed_vals']) > 0)
      optAllowValsExist = true;
  }
  var vAfterProcessing = null;
  
  switch(type) {
    // ********************** INTEGER *************************
    case ('int'):
        
      // check null
      if((optPermitNullExist == true) && (options['permit_null'] == 1))
        if (value == null || value == '')
          return {'err': 0, 'val': ''};

      // default value            
      if(optDefValExist == true)
        if (value == null || value == '')
          value = options['def_val'];
      
      // check allowed values
      if(optAllowValsExist == true)
        if(!in_array((value*1), options['allowed_vals']))
          return {'err': 1, 'val': value};
          
      // check regExp
      if(optRegExpExist == true) {
        if(options['reg_exp'].test(value) == false)
          return {'err': 1, 'val': value};
      } else { // standart regExp
        if(/^[0-9]+$/.test(value) == false)
          return {'err': 1, 'val': value};
      }
      
      // check range low
      if(optRangeLowExist == true) {
        if(/^[0-9]+$/.test(options['range_low']+'') == false) {
					alert('wrong range_low in validation, type int!');
					return 0;
        }else{ // range_low - is correct
          if((value*1) < (options['range_low']*1))
            return {'err': 1, 'val': value};
        }
      }
      
      // check range high
      if(optRangeHighExist == true) {
        if(/^[0-9]+$/.test(options['range_high']+'') == false) {
					alert('wrong range_high in validation, type int!');
          return 0;
        }else{ // range_high - is correct
          if((value*1) > (options['range_high']*1))
            return {'err': 1, 'val': value};
        }
      }
      
      //vAfterProcessing = parseInt(value);
      vAfterProcessing = (value*1);
      break;
    // ********************** FLOAT ************************* 
    case ('float'):

      // check null
      if((optPermitNullExist == true) && (options['permit_null'] == 1))
        if(value == null || value == '')
          return {'err': 0, 'val': ''};

      // default value            
      if(optDefValExist == true)
        if(value == null || value == '')
          value = options['def_val'];            

      // check allowed values
      if(optAllowValsExist == true)
        if(!in_array(parseFloat(value), options['allowed_vals']))
          return {'err': 1, 'val': value};
 
      // check regExp
      if(optRegExpExist == true) {
        if(options['reg_exp'].test(value) == false)
          return {'err': 1, 'val': value};
      } else { // standart regExp
        if(/^(([0-9]+(\.|\,)*[0-9]*)|([0-9]*(\.|\,)*[0-9]+))$/.test(value) == false)
          return {'err': 1, 'val': value};
      }
      
      // normalize
			value.replace(/,/, '.');
      //$value = preg_replace( '/,/', '.', $value );
      
      // check range low
      if(optRangeLowExist == true) {
        if(/^(([0-9]+(\.|\,)*[0-9]*)|([0-9]*(\.|\,)*[0-9]+))$/.test(options['range_low']+'') == false) {
					alert('wrong range_low in validation, type float!');
          return 0;
        }else{ // range_low - is correct
          if(parseFloat(value) < parseFloat(options['range_low']))
            return {'err': 1, 'val': value};
        }
      }
      
      // check range high
      if(optRangeHighExist == true) {
        if(/^(([0-9]+(\.|\,)*[0-9]*)|([0-9]*(\.|\,)*[0-9]+))$/.test(options['range_high']+'') == false) {
					alert('wrong range_high in validation, type float!');
          return 0;
        }else{ // range_high - is correct
          if(parseFloat(value) > parseFloat(options['range_high']))
            return {'err': 1, 'val': value};
        }
      }
      
      vAfterProcessing = parseFloat(value);
      break;
    // ********************** STRING *************************  
    case ('str'):

    	// check null
      if((optPermitNullExist == true) && (options['permit_null'] == 1))
        if(value == null || value == '')
          return {'err': 0, 'val': ''};

      // default value            
      if(optDefValExist == true)
        if(value == null || value == '')
          value = options['def_val'];
          
      // normalize
      value.replace(/[\n\t]/, ' ');
    	value.replace(/[\x01-\x1F]/, '');
      value = trim(value);

      // value is NULL ?
      if(value == null || value == '')
        return {'err': 1, 'val': value};
        
      // check allowed values
      if(optAllowValsExist == true) {
        if(!in_array(value, options['allowed_vals']))
          return {'err': 1, 'val': value};
      }   
        
      // check regExp
      if(optRegExpExist == true) {
        if(options['reg_exp'].test(value) == false)
          return {'err': 1, 'val': value};
      }
              
      // check range low
      if(optRangeLowExist == true) {
        if(/^[0-9]+$/.test(options['range_low']+'') == false) {
        	alert('wrong range_low in validation, type str!');
          return 0;
        }else{ // range_low - is correct
          if(value.length < (options['range_low']*1))
            return {'err': 1, 'val': value};
        }
      }
      
      // check range high
      if(optRangeHighExist == true) {
        if(/^[0-9]+$/.test(options['range_high']+'') == false) {
        	alert('wrong range_high in validation, type str!');
          return 0;
        }else{ // range_high - is correct
          if(value.length > (options['range_high']*1))
            return {'err': 1, 'val': value};
        }
      }
      
      vAfterProcessing = value;		
		  break;

    // ********************** TIME *************************  
    case ('time'):				

    	// check null
      if((optPermitNullExist == true) && (options['permit_null'] == 1))
        if(value == null || value == '')
          return {'err': 0, 'val': ''};    	
    	
      // default value            
      if(optDefValExist == true)
        if(value == null || value == '')
          value = options['def_val'];            

      // check allowed values
      if(optAllowValsExist == true)
        if(!in_array(value, options['allowed_vals']))
          return {'err': 1, 'val': value};
          
      // check regExp
      if(/^(([0-1][0-9])|([2][0-3])):[0-5][0-9]$/.test(value) == false)
      	return {'err': 1, 'val': value};
      
    	// check range low
      if(optRangeLowExist == true) {
        if(/^(([0-1][0-9])|([2][0-3])):[0-5][0-9]$/.test(options['range_low']) == false) {
					alert('wrong range_low in validation, type time!');
          return 0;
        }else{ // range_low - is correct
        	var comp_time = CompareTime(value, options['range_low']);
        	if(comp_time == -1)
        		return {'err': 1, 'val': value};
        }
      } 
      
      // check range high
      if(optRangeHighExist == true) {
        if(/^(([0-1][0-9])|([2][0-3])):[0-5][0-9]$/.test(options['range_high']) == false) {
					alert('wrong range_high in validation, type time!');
          return 0;
        }else{ // range_high - is correct
        	var comp_time = CompareTime(value, options['range_high']);
        	if(comp_time == 1)
        		return {'err': 1, 'val': value};
        }
      } 
     
      vAfterProcessing = value;
      break;

    // ********************** TIME with second *************************
    case ('times'):

      // check null
      if((optPermitNullExist == true) && (options['permit_null'] == 1))
        if(value == null || value == '')
          return {'err': 0, 'val': ''};     
      
      // default value            
      if(optDefValExist == true)
        if(value == null || value == '')
          value = options['def_val'];            

      // check allowed values
      if(optAllowValsExist == true)
        if(!in_array(value, options['allowed_vals']))
          return {'err': 1, 'val': value};
          
      // check regExp
      if(/^(([0-1][0-9])|([2][0-3])):[0-5][0-9]:[0-5][0-9]$/.test(value) == false)
        return {'err': 1, 'val': value};

      // check range low
      if(optRangeLowExist == true) {
        if(/^(([0-1][0-9])|([2][0-3])):[0-5][0-9]:[0-5][0-9]$/.test(options['range_low']) == false) {
          alert('wrong range_low in validation, type times!');
          return 0;
        }else{ // range_low - is correct
          var comp_times = CompareTime(value, options['range_low']);
          if(comp_times == -1)
            return {'err': 1, 'val': value};
        }
      } 
      
      // check range high
      if(optRangeHighExist == true) {
        if(/^(([0-1][0-9])|([2][0-3])):[0-5][0-9]:[0-5][0-9]$/.test(options['range_high']) == false) {
          alert('wrong range_high in validation, type times!');
          return 0;
        }else{ // range_high - is correct
          var comp_times = CompareTime(value, options['range_high']);
          if(comp_times == 1)
            return {'err': 1, 'val': value};
        }
      } 
     
      vAfterProcessing = value;
      break;      
      
    // ********************** DATE without time *************************
    case ('date'):
    	
    	// check null
      if((optPermitNullExist == true) && (options['permit_null'] == 1))
        if(value == null || value == '')
          return {'err': 0, 'val': ''}; 

      // default value
      if(optDefValExist == true)
        if(value == null || value == '')
          value = options['def_val'];    
          
      // check date_type
      if(optDateTypeExist == false) {
      	alert('wrong date_type in validation, type date!');
      	return 0;
      }
      
      // check allowed values
      if(optAllowValsExist == true)
        if(!in_array(value, options['allowed_vals']))
          return {'err': 1, 'val': value};

      // check regExp
      if(spCheckDate(value, options['date_type']) == false)
      	return {'err': 1, 'val': value};
            
      // normalize
	    if(options['date_type'] == 1){ // 1 - yyyy-mm-dd
	      var date_n = value.split('-');
	      var value_n = date_n[2]+'.'+date_n[1]+'.'+date_n[0];
	    }else
	      var value_n = value;
      	
	    // check range low
      if(optRangeLowExist == true) {
        if(spCheckDate(options['range_low'], 2) == false) {
					alert('wrong range_low in validation, type date!');
          return 0;
        }else{ // range_low - is correct
        	var comp_date = CompareDate(value_n, options['range_low']);
        	if(comp_date == -1)
        		return {'err': 1, 'val': value};
        }
      } 	
      	
      // check range high
      if(optRangeHighExist == true) {
        if(spCheckDate(options['range_high'], 2) == false) {
					alert('wrong range_high in validation, type date!');
          return 0;
        }else{ // range_high - is correct
        	var comp_date = CompareDate(value_n, options['range_high']);
        	if(comp_date == 1)
        		return {'err': 1, 'val': value};
        }
      }

      vAfterProcessing = value;
      break;

    // ********************** DATE with TIME *************************
    case ('datetime'):
      
      // check null
      if((optPermitNullExist == true) && (options['permit_null'] == 1))
        if(value == null || value == '')
          return {'err': 0, 'val': ''}; 

      // default value
      if(optDefValExist == true)
        if(value == null || value == '')
          value = options['def_val'];    
          
      // check date_type
      if(optDateTypeExist == false) {
        alert('wrong date_type in validation, type datetime!');
        return 0;
      }

      // check allowed values
      if(optAllowValsExist == true)
        if(!in_array(value, options['allowed_vals']))
          return {'err': 1, 'val': value};      
      
      // check regExp
      if(/^[0-9\-\.]{10}\s(([0-1][0-9])|([2][0-3])):[0-5][0-9]$/.test(value) == false)
        return {'err': 1, 'val': value};
  
      // partitioning datetime to date and time
      var arr_datatime = value.split(' ');
      var date = arr_datatime[0];
      var time = arr_datatime[1];
        
      //check date
      if(spCheckDate(date, options['date_type']) == false)
        return {'err': 1, 'val': value};
            
      // normalize
      if(options['date_type'] == 1){ // 1 - yyyy-mm-dd
        var date_sp = date.split('-');
        var date_n = date_sp[2]+'.'+date_sp[1]+'.'+date_sp[0];
      }else
        var date_n = date;

      // check range low
      if(optRangeLowExist == true) {
        if(/^[0-9\-\.]{10}\s(([0-1][0-9])|([2][0-3])):[0-5][0-9]$/.test(options['range_low']) == false) {
          alert('wrong range_low in validation, type datetime!');
          return 0;
        }
        var datetime_rl = options['range_low'].split(' ');
        var date_rl = datetime_rl[0];
        var time_rl = datetime_rl[1];
        if(spCheckDate(date_rl, 2) == false) { // dd.mm.yyyy
          alert('wrong range_low in validation, type datetime!');
          return 0;
        }
        
        var comp_date = CompareDate(date_n, date_rl);
        if(comp_date == -1)
          return {'err': 1, 'val': value};
        if(comp_date == 0) {
          var comp_time = CompareTime(time, time_rl);
          if(comp_time == -1)
            return {'err': 1, 'val': value};
        }
      }

      // check range high
      if(optRangeHighExist == true) {
        if(/^[0-9\-\.]{10}\s(([0-1][0-9])|([2][0-3])):[0-5][0-9]$/.test(options['range_high']) == false) {
          alert('wrong range_high in validation, type datetime!');
          return 0;
        }
        var datetime_rh = options['range_high'].split(' ');
        var date_rh = datetime_rh[0];
        var time_rh = datetime_rh[1];
        if(spCheckDate(date_rh, 2) == false) { // dd.mm.yyyy
          alert('wrong range_high in validation, type datetime!');
          return 0;
        }
        
        var comp_date = CompareDate(date_n, date_rh);
        if(comp_date == 1)
          return {'err': 1, 'val': value};
        if(comp_date == 0) {
          var comp_time = CompareTime(time, time_rh);
          if(comp_time == 1)
            return {'err': 1, 'val': value};
        }
      }      

      vAfterProcessing = value;
      break;

    // **************** DATE with TIME with seconds *******************
    case ('datetimes'):

      // check null
      if((optPermitNullExist == true) && (options['permit_null'] == 1))
        if(value == null || value == '')
          return {'err': 0, 'val': ''}; 

      // default value
      if(optDefValExist == true)
        if(value == null || value == '')
          value = options['def_val'];    
          
      // check date_type
      if(optDateTypeExist == false) {
        alert('wrong date_type in validation, type datetimes!');
        return 0;
      }

      // check allowed values
      if(optAllowValsExist == true)
        if(!in_array(value, options['allowed_vals']))
          return {'err': 1, 'val': value};      
      
      // check regExp
      if(/^[0-9\-\.]{10}\s(([0-1][0-9])|([2][0-3])):[0-5][0-9]:[0-5][0-9]$/.test(value) == false)
        return {'err': 1, 'val': value};
  
      // partitioning datetime to date and time
      var arr_datatime = value.split(' ');
      var date = arr_datatime[0];
      var time = arr_datatime[1];
        
      //check date
      if(spCheckDate(date, options['date_type']) == false)
        return {'err': 1, 'val': value};
            
      // normalize
      if(options['date_type'] == 1){ // 1 - yyyy-mm-dd
        var date_sp = date.split('-');
        var date_n = date_sp[2]+'.'+date_sp[1]+'.'+date_sp[0];
      }else
        var date_n = date;

      // check range low
      if(optRangeLowExist == true) {
        if(/^[0-9\-\.]{10}\s(([0-1][0-9])|([2][0-3])):[0-5][0-9]:[0-5][0-9]$/.test(options['range_low']) == false) {
          alert('wrong range_low in validation, type datetimes!');
          return 0;
        }
        var datetime_rl = options['range_low'].split(' ');
        var date_rl = datetime_rl[0];
        var time_rl = datetime_rl[1];
        if(spCheckDate(date_rl, 2) == false) { // dd.mm.yyyy
          alert('wrong range_low in validation, type datetimes!');
          return 0;
        }
        
        var comp_date = CompareDate(date_n, date_rl);
        if(comp_date == -1)
          return {'err': 1, 'val': value};
        if(comp_date == 0) {
          var comp_time = CompareTime(time, time_rl);
          if(comp_time == -1)
            return {'err': 1, 'val': value};
        }
      }

      // check range high
      if(optRangeHighExist == true) {
        if(/^[0-9\-\.]{10}\s(([0-1][0-9])|([2][0-3])):[0-5][0-9]:[0-5][0-9]$/.test(options['range_high']) == false) {
          alert('wrong range_high in validation, type datetimes!');
          return 0;
        }
        var datetime_rh = options['range_high'].split(' ');
        var date_rh = datetime_rh[0];
        var time_rh = datetime_rh[1];
        if(spCheckDate(date_rh, 2) == false) { // dd.mm.yyyy
          alert('wrong range_high in validation, type datetimes!');
          return 0;
        }
        
        var comp_date = CompareDate(date_n, date_rh);
        if(comp_date == 1)
          return {'err': 1, 'val': value};
        if(comp_date == 0) {
          var comp_time = CompareTime(time, time_rh);
          if(comp_time == 1)
            return {'err': 1, 'val': value};
        }
      }      

      vAfterProcessing = value;
      break;      
      
    default:
    	alert('wrong type in validation!');
    	return 0;
	}

  return {'err': 0, 'val': vAfterProcessing};
}

function spCheckDate(value, type) {
  if (value == '')
    return false;
  
  var matches = null;
  if(type == 1) { // 1 - yyyy-mm-dd 
  	if((matches = /^(\d{4})\-(\d{2})\-(\d{2})$/.exec(value)) == null)
      return false;
  	var year = (matches[1]*1); 
    var month = (matches[2]*1); 
    var day = (matches[3]*1);
  } else { // 2 - dd.mm.yyyy
  	if((matches = /^(\d{2})\.(\d{2})\.(\d{4})$/.exec(value)) == null)
      return false;    
  	var year = (matches[3]*1); 
    var month = (matches[2]*1); 
    var day = (matches[1]*1);
  }
  if(month > 12 || month < 1 || year > 2030 || year < 2008)
    return false;
  var daysOnMonth = (DaysPerMonth(year, (month-1))*1);
  if(day > daysOnMonth)
  	return false;
  
  return true;
}

function IsLeapYear (Year) {
  return ((Year % 4) == 0) && (((Year % 100) != 0) || ((Year % 400) == 0))
}

function DaysPerMonth (Year, Month) {
   DaysInMonth = new Array (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
   if (Month == -1) Month = 11;
   days=DaysInMonth[Month];
   if ((Month == 1) && IsLeapYear(Year)) {days++;}
   return days
}

function CompareDate (date1, date2) {
	// rc: 1 - date1 > date2 / 0 - date1 = date2 / -1 - date1 < date2
	
	var date1s = date1.split('.');
	var date2s = date2.split('.');
	// 0 - day / 1 - month / 2 - year
	
	if((date1s[2]*1) > (date2s[2]*1))	
		return 1;
	if((date1s[2]*1) < (date2s[2]*1))
		return -1;
	if((date1s[1]*1) > (date2s[1]*1))
		return 1;
	if((date1s[1]*1) < (date2s[1]*1))
		return -1;
	if((date1s[0]*1) > (date2s[0]*1))
		return 1;
	if((date1s[0]*1) < (date2s[0]*1))
		return -1;

	return 0;
}

function CompareTime (time1, time2) {
	//rc: 1 - time1 > time2 / 0 - time1 = time2 / -1 - time1 < time2
	
	var time1s = time1.split(':');
	var time2s = time2.split(':');
	var ftimes = false;
	if(sizeof(time1s) == 3)
	  ftimes = true;
	//0 - hours / 1 - minutes / 2 - seconds
	
	if((time1s[0]*1) > (time2s[0]*1))
		return 1;
	if((time1s[0]*1) < (time2s[0]*1))
		return -1;
	if((time1s[1]*1) > (time2s[1]*1))
		return 1;
	if((time1s[1]*1) < (time2s[1]*1))
		return -1;
	if(ftimes == true) {
  	if((time1s[2]*1) > (time2s[2]*1))
      return 1;
    if((time1s[2]*1) < (time2s[2]*1))
      return -1;
	}
	
	return 0;
}

/**************************** Validation *****************************/
/*********************************************************************/
function toggle_tab(id)
{
    destroyPopupWindow({'fadeout': false});

    var jTab = $('#tab_' + id);
    if (jTab.length)
    {
        $('[id^="tab_"]').hide();
        jTab.show();
        
        $('[id^="t_text"]').hide();
        $('[id^="t_a"]').show();
        
        $('#t_text_' + id).show();
        $('#t_a_' + id).hide();
        
        _pset.tab_selected = id;
    }
}

function show_validation_advice(id)
{
    var jAdvice = $('#validation_advice_' + id);
    jAdvice.show();
}

function toggle_el(id)
{
    $('#' + id).toggle();
}

function add_country_selection()
{
    var str = '<div class="spPanAddFileImg" onlick="alert()"></div>';
    var jTd = $('#blt\\[bw_mask\\]\\[new_0\\]');
    jTd[0].innerHTML = str + jTd[0].innerHTML;
}

function keep_session_alive()
{
    touch_server_persistant(20*60*1000);
}

function touch_server_persistant(delay)
{
    set_delayed_call();
    
    function touch_server()
    {
        JsHttpRequest.query(
            _pset.PATH_TO_ROOT + '/backend.php',
            {
                'action'            : 'empty'
            },
            
            function(result, errors)
            {  
                if (typeof(result.ok) != 'undefined' && result.ok == 1)
                {
                    set_delayed_call();
                }
            }, 
            true
        );
    }
    
    function set_delayed_call()
    {
        setTimeout(function() {touch_server() }, delay);
    }
}







function touch_server111(persistant_call)
{
    var delay = 20*60*1000;
    
    var inPersistant = return_persistant();
    if (inPersistant == 1)
    {
        setTimeout(function() {touch_server(delay) }, delay);
    }
    else 
    {
    
        JsHttpRequest.query(
            _pset.PATH_TO_ROOT + '/backend.php',
            {
                'action'            : 'empty'
            },
            
            function(result, errors)
            {  
                if (typeof(result.ok) != 'undefined' && result.ok == 1)
                {
                    if (typeof(persistant_call) != 'undefined')
                    {
                        setTimeout(function() {touch_server(1) }, 20*60*1000);
                        
                    }
                }
    //                ;
    //            else if (typeof(result.have_no_auth) && result.have_no_auth == 1)
    //                ;
    //            else    
                    
                
            }, 
            true
        );
    }
    
    function return_persistant()
    {
        if (typeof(persistant_call) != 'undefined')
            return persistant_call;
        else
            return false;
    }
}

function select_on_first_click(el)
{
    alert(el.hasFocus());
    if (!el.hasFocus())
        el.select();
}

    
        

function get_from_textarea(elem)
{
    return elem.innerHTML;
}

function make_popup_html(elem)
{
    var content = get_from_textarea(elem);
    var win = window.open(url, win_name, 'fullscreen=no, toolbar=no, scrollbars=no, directories=no, status=no, menubar=yes, resizable=yes'); 
	win.focus();
    
}


function convert_val_to_hidden(name, value)
{
    //return '<input type="hidden" name="' + name + '" value="' + value + '">';
    return '<textarea name="' + name + '" style="display:none;">' + value + '</textarea>';
}

function convert_arr_to_hidden(arr, name_prefix)
{
    //rrr = arr;
    var str = '', add_name_prefix = '';
    
    if (typeof(name_prefix) == 'string')
        add_name_prefix = name_prefix;
        
    if (sizeof(arr) == 1)
    {
        for (var text_id in arr)
        {
            if (typeof(arr[text_id]) == 'string' || typeof(arr[text_id]) == 'number')
            {
                str += convert_val_to_hidden(text_id, arr[text_id]);
                return str;
            }
            else
            {
                break;
            }
        }
    }
    
    if (sizeof(arr))
    {
        for (var text_id in arr)
        {
            if (sizeof(arr[text_id]))
            {
                for (var field in arr[text_id])
                {
                    var val = arr[text_id][field];
                    var new_name_prefix = field + '[' + text_id + ']';
                    if (! (typeof(val) == 'undefined' || val == '' || val == 'undefined')  )
                    {
                        if (typeof(val) == 'string' || typeof(val) == 'number')
                        {
                            str += convert_val_to_hidden(add_name_prefix + new_name_prefix, val);
                        }
                        else if (typeof(val) == 'object')
                        {
                            str += convert_arr_to_hidden(val, new_name_prefix);
                        }
                    }
                }
            }
        }
    }
    return str;
}

function open_window_with_post_params(arr)
{
    form = document.createElement('form');
    form.action = _pset.PATH_TO_ROOT + '/get_file.php';
    form.method = 'post';
    form.enctype = 'multipart/form-data';
    form.name = 'hidden_data';
    
    var data_div = document.createElement('div');
    
    data_div.innerHTML = convert_arr_to_hidden(arr);
    
    form.appendChild(data_div);
    document.body.appendChild(form);
    
    form.submit();
    return false;
}



/* ====================================================================== */
/* From Callme module */

var oTimeTable;

$(document).ready(function() 
{
    oTimeTable = time_table_component();
    
    
    //get_callme_html('area_2');

    
});


var singletonFactory = new singletonFactoryClass();
function singletonFactoryClass()
{
    var singletonArr = new Object;
    this.register = function(classToUse)
    {
        var className = classToUse.toString();
    	className = className.substring( className.indexOf(" ") + 1, className.indexOf("(") );
    	
        if (typeof singletonArr[className] == 'undefined')
        {
            singletonArr[className] = new singletonKillerClass(classToUse);
            return singletonArr[className];
        }
        else
        {
            if (singletonArr[className].get_instance() instanceof classToUse)
            {
                return singletonArr[className];
            }
            else
            {
                alert ('Type mismatch');
            }
        }
    }
}


function singletonKillerClass(classToUse)
{
    // public:
    this.new_instance = function()
    {
        return pick_instance(1);
    }
    
    this.get_instance = function()
    {
        return pick_instance(0);
    }
    
    this.kill_instance = function()
    {
        return sDestructor;
    }
    
    function pick_instance(get_new)
    {
        if (instance == null)
        {
            return sConstructor();
        }
        else if (get_new)
        {
            sDestructor();
            return sConstructor();
        }
        else
        {
            return instance;
        }
    }
    
    this.hello = 'Greetings, my lord!';

    function isFriend(oFriend)
    {
        if (oFriend instanceof singletonFactoryClass)
            return true;
        else
            return false;
    }
    
    // private:
    var instance = null;
    
    function sConstructor()
    {
        instance = new classToUse();
        instance.ttConstructor();
        return instance;
    }
    
    function sDestructor()
    {
        instance.ttDestructor();
        delete instance;
        instance = null;
    }
}


    
function time_table()
{
    this.oComponents = new Object;
    this.hello = 'On your duty, sir!';
    
    //alert('time_table finished');
}

with(time_table)
{
    prototype.ttConstructor = function()
    {
        //alert('call - ttConstructor');
        this.oComponents.oSwitchCboxBlockTime    = new switchCboxBlock('switch_time', 'time_block');
        this.oComponents.oSwitchCboxConstraint   = new switchCboxConstraint('_ph_weekday_type');
        
        //this.oComponents.oSwitchCboxBlockDate    = new switchCboxBlock('switch_date', 'date_block');
        //add_calendar('_ph_valid_from', '_ph_valid_from_icon');
        //add_calendar('_ph_valid_until', '_ph_valid_until_icon');
    }
        
    prototype.ttDestructor = function()
    {
        //alert('call - ttDestructor');
        for (var i in this.oComponents)
        {
            this.oComponents[i].destructor();
        }
    }
}

//with (time_table = new function() { this.oComponents = new Object; } )
//{
//    prototype.ttConstructor = function()
//    {
//        //alert('call - ttConstructor');
//        this.oComponents.oSwitchCboxBlockTime    = new switchCboxBlock('switch_time', 'time_block');
//        this.oComponents.oSwitchCboxConstraint   = new switchCboxConstraint('_ph_weekday_type');
//        
//        //oComponents.oSwitchCboxBlockDate    = new switchCboxBlock('switch_date', 'date_block');
//        //add_calendar('_ph_valid_from', '_ph_valid_from_icon');
//        //add_calendar('_ph_valid_until', '_ph_valid_until_icon');
//
//    }
//    
//    prototype.ttDestructor = function()
//    {
//        //alert('call - ttDestructor');
//        for (var i in oComponents)
//        {
//            this.oComponents[i].destructor();
//        }
//    }
//    
//    prototype.hello = 'On your duty, sir!';
//}






function time_table_component()
{
    return singletonFactory.register(time_table);
}


function switchCboxBlock(cboxID, blockID)
{
    if (!checkInput())
        alert('bad input!');
    
    var jSwitchCbox;
    var jSwitchBlock;
    
    function switch_block(on)
    {
        if (on)
        {
            jSwitchBlock.show();
        }
        else
        {
            jSwitchBlock.hide();
        }
    }
    
    function sCboxEvent()
    {
        if (jSwitchCbox.is(':checked'))
        {
            switch_block(true);
        }
        else
        {
            switch_block(false);
        }
    }
    
    this.setPosition = function(on)
    {
        if (on)
        {
            jSwitchCbox.attr('checked', true);
        }
        else
        {
            jSwitchCbox.attr('checked', false);
        }
        sCboxEvent();
    }
    
    this.getPosition = function()
    {
        return jSwitchCbox.attr('checked');
    }
    
    
    this.constructor = function()
    {
        jSwitchCbox  = $('input:checkbox[id="' + cboxID + '"]');
        jSwitchBlock = $('#' + blockID);
        jSwitchCbox.bind('click', sCboxEvent);
        sCboxEvent();
    }
    
    this.destructor = function()
    {
        jSwitchCbox.unbind('click', sCboxEvent);
        jSwitchCbox = null;
        jSwitchBlock = null;
    }
    
    function checkInput()
    {
        if (typeof(cboxID) != 'string' || typeof(blockID) != 'string')
            return 0;
            
        return 1;
    }
    
    
    this.constructor();
}



//with (switchCboxBlock)
//{
//    prototype.setPosition = function(on)
//    {
//        if (on)
//        {
//            jSwitchCbox.attr('checked', true);
//        }
//        else
//        {
//            jSwitchCbox.attr('checked', false);
//        }
//        sCboxEvent();
//    }
//    
//    prototype.getPosition = function()
//    {
//        return jSwitchCbox.attr('checked');
//    }
//    
//    
//    prototype.constructor = function(cboxID, blockID)
//    {
//        jSwitchCbox  = $('input:checkbox[id="' + cboxID + '"]');
//        jSwitchBlock = $('#' + blockID);
//        jSwitchCbox.bind('click', .sCboxEvent);
//        sCboxEvent();
//    }
//    
//    prototype.destructor = function()
//    {
//        jSwitchCbox.unbind('click', sCboxEvent);
//        jSwitchCbox = null;
//        jSwitchBlock = null;
//    }
//}


function switchCboxConstraint(cboxName)
{
    if (!checkInput())
        alert('bad input!');
    
    var jSwitchCboxArr;
    
    function haveSomeChecked()
    {
        var hasChecked = false;
        for (var i=0; i<jSwitchCboxArr.length; i++)
        {
            if ($(jSwitchCboxArr[i]).is(':checked'))
            {
                hasChecked = true;
                break;
            }
        }
       return hasChecked;
    }
    
    function setSomeChecked(skipElement)
    {
        for (var i=0; i<jSwitchCboxArr.length; i++)
        {
            if (jSwitchCboxArr[i] != skipElement)
            {
                $(jSwitchCboxArr[i]).attr('checked', true)
                break;
            }
        }
    }
    
    function sCboxEvent()
    {
        if ($(this).not(':checked'))
        {
            if (!haveSomeChecked())
            {
                setSomeChecked(this);
            }
        }
        else
            ;
    }
    
    this.constructor = function()
    {
        jSwitchCboxArr = $('input:checkbox[name="' + cboxName + '"]');
        jSwitchCboxArr.bind('click', sCboxEvent);
        sCboxEvent();
    }
    
    this.destructor = function()
    {
        jSwitchCboxArr.unbind('click', sCboxEvent);
    }
    
    function isChecked(jEl)
    {
        return jEl.attr('checked');
    }
    
    function setChecked(jEl)
    {
         jEl.attr('checked', true)
    }
    
    function setNotChecked(jEl)
    {
         jEl.attr('checked', false)
    }
    
    this.setValues = function(flagArr)
    {
        if (typeof(flagArr) != 'undefined')
        {
            for (var k=0; k<flagArr.length; k++)
            {
                if (flagArr[k])
                    setChecked($(jSwitchCboxArr[k]));
                else
                    setNotChecked($(jSwitchCboxArr[k]));
            }
            return true;
        }
        return false;
    }
    
    this.getValues = function()
    {
        var arr = new Object;
        for (var i=0; i<jSwitchCboxArr.length; i++)
        {
            arr[i] = (isChecked($(jSwitchCboxArr[i]))) ? jSwitchCboxArr[i].value : 0;
        }
        return arr;
    }
    
    function checkInput()
    {
        if (typeof(cboxName) != 'string')
            return 0;
            
        return 1;
    }
    
    
    this.constructor();
}



function edit_time_table(elem, id_row, event)
{
    if (typeof(id_table) == 'undefined')
        var id_table = 'ph_table';
    
    _pset.js_control_table[id_table].time_table_edit_id = id_row;
    var time_table = _pset.js_control_table[id_table].time_table;
    
    initMessage(event, JSLocaleCore['set_sched'], get_time_table_template(), get_position(), get_options());
    
    
    function get_time_table_template()
    {
        if (typeof(_pset.time_table_template) == 'undefined')
        {
            var tt = $('#edit_time_table')[0];
            _pset.time_table_template = tt.innerHTML;
            tt.parentNode.removeChild(tt);
        }
        
        return _pset.time_table_template;
    }
    
    function get_options()
    {
        var opt = 
        {
            outclose:             false,
            id:                   'time_table',
            call_back_funct:      on_init
        }  
        
        return opt;  
    }
    
    function get_position()
    {
        return {'width': 350, 'height': 220, 'left': -398, 'top': -8};
    }
    
    function on_init()
    {
        var oTable = oTimeTable.new_instance();
        
        with (oTable.oComponents)
        {
            oSwitchCboxConstraint.setValues(get_weekdays_arr());    
        
            var jTime = $('[name=switch_time]');
            if (time_table[id_row].ph_start_time || time_table[id_row].ph_stop_time)
            {
                oSwitchCboxBlockTime.setPosition(true);
            }
            
            var jDate = $('[name=switch_date]');
            if (time_table[id_row].ph_valid_from || time_table[id_row].ph_valid_until)
            {
                if (typeof (oSwitchCboxBlockDate) != 'undefined')
                    oSwitchCboxBlockDate.setPosition(true);
            }
        }
            
        
        if (typeof(time_table[id_row]) != 'undefined' && sizeof(time_table[id_row]))
        {
            for (var field_name in time_table[id_row])
            {
                //alert(field_name + ' val = ' + time_table[id_row][field_name]);
                if (field_name != '_ph_weekday_type' && typeof(time_table[id_row][field_name]) != 'undefined' && trim(time_table[id_row][field_name]) != '')
                {
                    var jInput = $('[name=_' + field_name + ']');
                    if (jInput.length)
                    {
                        var tInput = jInput[0];
                        tInput.value = time_table[id_row][field_name];
                        
                        if (!$(tInput).is('.hasDatepicker'))
                        { 
                            $(tInput).focus();
                            $(tInput).blur();    
                        }
                    }
                }
            }
        }
        
        //alert('end of edit_time_table()');
    }
    
    
    function get_weekdays_arr()
    {
        var flagArr = new Array;
        if (time_table[id_row].ph_weekday_type == 1)
        {
            flagArr[0] = 1;
            flagArr[1] = 0;
        }
        else if (time_table[id_row].ph_weekday_type == 2)
        {
            flagArr[0] = 0;
            flagArr[1] = 1;
        }
        else
        {
            flagArr[0] = 1;
            flagArr[1] = 1;
        }
        return flagArr;
    }
}


function save_time_table()
{
    var oTable = oTimeTable.get_instance();
    
    if (typeof(id_table) == 'undefined')
        var id_table = 'ph_table';
    
    var id = _pset.js_control_table[id_table].time_table_edit_id;
    var time_table = _pset.js_control_table[id_table].time_table;
    
    for (var field_name in time_table[id])
    {
        if (field_name == 'ph_valid_from' || field_name == 'ph_valid_until')
        {
            if (typeof (oSwitchCboxBlockDate) != 'undefined' && !oTable.oComponents.oSwitchCboxBlockDate.getPosition())
            {
                time_table[id][field_name] = null;
                continue;
            }
        }
        
        if (field_name == 'ph_start_time' || field_name == 'ph_stop_time')
        {
            if (!oTable.oComponents.oSwitchCboxBlockTime.getPosition())
            {
                time_table[id][field_name] = null;
                continue;
            }
        }
        
        if (field_name == 'ph_weekday_type')
        {
            var arr = oTable.oComponents.oSwitchCboxConstraint.getValues();
            
            if (arr[0] && arr[1])
                time_table[id][field_name] = null;
                
            else if (arr[0])
                time_table[id][field_name] = arr[0];
                
            else if (arr[1])
                time_table[id][field_name] = arr[1];
                
            continue;
        }
        
        var jField = $('[name=_' + field_name + ']');
        if (!jField.length) continue;
        
        var val = jField[0].value;
        var save_val = true;
        
        for (var i in _pset.default_text_values) 
	    {
            if (val == _pset.default_text_values[i]) 
		    {
                save_val = false;
                val = '';
                break;
		    }     
	    }
	    
        time_table[id][field_name] = val
    }
    
//    if (time_table[id]['ph_start_time'] > time_table[id]['ph_stop_time'])
//    {
//        alert(JSLocaleCore['no_mid']);
//        return;
//    }
    
    var jTime = $('[name=switch_time]');
    if (jTime.attr('checked'))
    {
        if (time_table[id]['ph_start_time'] != '' && time_table[id]['ph_start_time'] == time_table[id]['ph_stop_time'])
        {
            alert(JSLocaleCore['mode_24_7']);
            time_table[id]['ph_start_time'] = time_table[id]['ph_stop_time'] = null;
        }    
    }
    else
    {
        time_table[id]['ph_start_time'] = time_table[id]['ph_stop_time'] = null;
    }
    
    
    
    bind_time_table();
    //$('#edit_time_table').fadeOut();
    destroyPopupWindow({'fadeout': false});
}


function bind_time_table(id_table)
{
    if (typeof(id_table) == 'undefined')
        var id_table = 'ph_table';
    
    var time_table = _pset.js_control_table[id_table].time_table;
        
    if (typeof(time_table) != 'undefined')
    {
        //time_table[new_id_text] = new Array();
        for (var text_id in time_table)
        {
            //time_table[text_id]
            var td_id = id_table + '_td_' + text_id;
            
            //alert(td_id);
            //alert('#' + td_id);
            //$('#' + td_id)[0].innerHTML = '';
            
            var str = '', str_time = '';
            var el = time_table[text_id];
            
//            alert(el.length);
//            alert(el.ph_weekday_type);

            //alert('size='+sizeof(el));
            
            if (sizeof(el))
            {
                for (var i in el)
                {
                    if (el[i] == null) el[i] = '';
                }
                
                if (el.ph_valid_from || el.ph_valid_from_time)
        	        str_time += " "+JSLocaleCore['rows']['from']+" " + el.ph_valid_from + " " + el.ph_valid_from_time;
        	       
    	        if (el.ph_valid_until || el.ph_valid_until_time)
        	        str_time += " "+JSLocaleCore['rows']['to']+" " + el.ph_valid_until + " " + el.ph_valid_until_time;
            	 
        	    if (el.ph_start_time)
        	        str_time += " "+JSLocaleCore['rows']['from']+" " + el.ph_start_time;
        	       
    	        if (el.ph_stop_time)
        	        str_time += " "+JSLocaleCore['rows']['to']+" " + el.ph_stop_time;
        	    
        	    if (el.ph_weekday_type == 1)
                    str = JSLocaleCore['days_type']['on'];
            	   
        	    else if (el.ph_weekday_type == 2)
        	        str = JSLocaleCore['days_type']['off'];
        	       
    	        else if (str_time != '')
        	        str = JSLocaleCore['days_type']['all'];
    	        
    	        else
    	            str = JSLocaleCore['days_type']['24_7'];
        	           
	            str += str_time;
    	        //str = '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td>' + str + '</td><td align="right"><a href="javascript:void(0)" onclick="edit_time_table(this, ' + text_id + ')">изменить</a>';
    	        
    	        str = str + ' [ <a href="#" onclick="edit_time_table(this, \'' + text_id + '\', event); return false;">'+JSLocaleCore['change']+'</a> ]';
                
    	        
    	        //alert(td_id);
                document.getElementById(td_id).innerHTML = str;
            }
        }
    }
    
}


function callme_prepare_data()
{
    if (_pset.incomplete_reg == 1  )
	{
		var err_str = JSCoreLocale['err_end_reg'] + JSCoreLocale['err_end_reg2'] + '</br><a href=">' 
		+ _pset.PATH_TO_ROOT_SCRIPT + '/registration2_show?step=2">' + JSCoreLocale['end_reg_link'] + '</a>';
		
		$.blockClickMSG(JSCoreLocale['click_err']['title'], err_str, 'cancel');
		return false;
	} 
	
	//var tt_params = $.toJSON(_pset.time_table);
    //$('#time_table_arr')[0].value = tt_params;
    var add_data_div = document.createElement('div');
    
    var time_table = _pset.js_control_table['ph_table'].time_table;
    
    var hidden_inputs = convert_arr_to_hidden(time_table);
    
    if (typeof(_pset.tab_selected) != 'undefined')
        hidden_inputs += convert_val_to_hidden('tab_selected', _pset.tab_selected);
    
    $('form#data')[0].appendChild(add_data_div);
    

    for (var table_id in _pset.js_control_table)
    {
        var is_empty = _pset.js_control_table[table_id].is_empty;
        if (typeof(is_empty) != 'undefined')
        {
            hidden_inputs += convert_val_to_hidden(table_id + '[is_empty]', is_empty);
        }
    }
    
    //alert(hidden_inputs);
    
    add_data_div.innerHTML = hidden_inputs;

    return true;
}


/* From Callme module (END)*/
/* ====================================================================== */

function init_def_val(jElem, def_val)
{
    jElem.bind('focus', function() { 
        checkEmptyIn(this, def_val)
    });
    
    jElem.bind('blur', function() { 
        checkEmptyOut(this, def_val)
    });
    
    jElem.focus();
    jElem.blur();
}


function mergeObjects(o1, o2)
{
    if (typeof(o1) == 'object' && typeof(o2) == 'object' )
    {
        var oRet = o1;
        for (var i in o2)
        {
            if (!oRet[i])
                oRet[i] = o2[i]
        }
        return oRet;
    }
    return false;
}

function show_ajax_auth_form() {
	
}

function notifyWrongInfo(jEl)
{
    jEl
      .bind('mouseover', function() { formMsg(this) } )
      .bind('mouseout',  function() { $('#JT').remove() } )
      .bind('keyup', onChangeEvent)
      .bind('change', onChangeEvent)
      ;
      
    function onChangeEvent()    
    {
        var inputEl = this;
        var length = this.value.length;
        //var valid_reg = new RegExp("^[a-zA-Zа-яА-ЯёЁ0-9 !\"#\\$%&()'*+,-./:;<=>?@\[\\\]^_`{|}~]*$");
        var valid_reg = new RegExp(".*"); // GCH: 2010.05.04 - pass anything now
        
        notifyStatus();
        
        function validate(val)
        {
            if (!trim(val)) return true;
            return valid_reg.test(val);
        }
        function notifyStatus()
        {
            if ( validate(inputEl.value) )
            {
                removeFormSpecialFormatting( $(inputEl) );
            } 
            else 
            {
                setFormFormattingWarning( $(inputEl) );
            }
        }
    }
        
    function formMsg(elem) 
    {
        var name = elem.name;
        var id = elem.id;
        var titlehtml = '';
        var bodyhtml = '';
        var width = 350;
        var height = 0;
        
        titlehtml = '<span style="color:#333333;"><b>'+JSLocaleCore['msg_format']['title']+'</b></span>';
        
        bodyhtml = '<p>'+JSLocaleCore['msg_format']['body']+'</p>';      
        height = 60;
        
        JT_show(elem, titlehtml, bodyhtml, width, height);
    }
}


//function phoneField()
//{
//    //_prepareList();
//    
//    function _prepareList()
//    {
//        this.contName = [];
//        this.contPhone = [];
//        
//        //str = '';
//        //this.contName['bbb'] = 1;
//        for (var i in _pset.addr_book)
//        {
//            this.contName[_pset.addr_book[i].name] = _pset.addr_book[i].phone;
//            this.contPhone[_pset.addr_book[i].phone] = _pset.addr_book[i].name;
//            //str += _pset.addr_book[i].phone;
//        }
//        
//        //alert(this.contPhone['79168144819']);
////        alert(this.contName.toString());
////        alert(this.contPhone.toString());
//    }
//    function search(val)
//    {
//        var inArr = _pset.addr_book;
//        
//        var regPhone = new RegExp("^[0-9]{1}[0-9\.\,]+[0-9]{1}$", "g");
//        var regVal = new RegExp("^" + val, 'i');
//        var seekNums = regPhone.test(val);
//        
//        var retArr = [];
//	    
//        for (var i in inArr)
//        {
//            if (seekNums && regVal.test(inArr[i].phone)
//            {
//                retArr.push(inArr[i]);
//            }
//            else if (regVal.test(inArr[i].name))
//            {
//                retArr.push(inArr[i]);
//            }
//        }
//    
//	    return retArr;
//    }
//    
//    function 
//}

//$(document).ready(function() {
//    phoneField();
//});
//
//







//function LiveSearch(field, div) { this.construct(field, div) }
//LiveSearch.prototype = {
//  url:     (window.BASE_SITE || '') + '/dk_improve/live/LiveSearch/load_search.php',
//  field:   null,
//  div:     null,
//  prevQ:   '',
//  prevT:   null,
//  timeout: null,
//  
//  construct: function(field, div) {
//    this.field = field;
//    this.div = div;
//    this.prevT = new Date();
//    
//    var th = this;
//    addEvent(field, 'onkeydown', function(e) {
//      th.prevT = new Date();
//      if (e.keyCode == 13) th.onchangeControl(this.value, 100);
//      return true;
//    })
//    addEvent(field, 'onkeyup', function(e) { 
//      if (e.keyCode == 13) return true;
//      th.onchangeControl(this.value, e.keyCode==32? 1000 : null);
//      return true;
//    })
//    addEvent(field, 'onfocus', function() {
//      // stupid Mozilla sometimes loses focus on DIV repainting :-(
//      th.focused = true;
//      return true;
//    })
//    addEvent(field, 'onblur', function() {
//      th.onchangeControl(field.value, 0);
//      th.focused = false;
//      return true;
//    })
//  },
//  
//  onchangeControl: function(text, dt) {
//    var t = new Date();
//    var wait = 0;
//    if (dt == null) dt = 2000;
//    
//    if (t.getTime() - this.prevT.getTime() < dt) {
//      this.prevT = t;
//      wait = dt;
//    }
//    
//    var th = this;
//    if (this.timeout) { clearTimeout(this.timeout); this.timeout=null; }
//    this.timeout = setTimeout(function() { th.prevT = t; th.timeout=null; th.onchange(text) }, wait);
//  },
//  
//  onchange: function(text, force) {
//    var q = this.clean(text);
//    if (q != this.prevQ && q != "") {
//      this.prevQ = q;
//      var th = this;
//      var req = new JsHttpRequest();
//      req.onreadystatechange = function() {
//        if (window.hackerConsole) window.hackerConsole.out(req.responseText, '', 'Shell');
//        if (req.readyState != 4) return;
//        if (!req.responseJS || !Math.round(req.responseJS[0])) {
//          th.div.style.display = "none";
//          return;
//        }
//        th.div.innerHTML = req.responseJS[1];
//        if (window.livePreview) {
//          var links = th.div.getElementsByTagName('A');
//          for (var i=0; i<links.length; i++) {
//            window.livePreview.attachLink(links[i]);
//          }
//        }
//        th.div.style.display = "block";
//        if (th.focused) th.field.focus();
//      }
//      req.caching = true;
//      req.open('GET', th.url, true);
//      req.send({ 'q': q });
//    }
//  },
//  
//  clean: function(text) {
//    var spl = text.split(/[\s~!@#&$%^*()\[\]{}:\"<>?`=;\',\.\/\\|\-]+/i);
//    var words = [];
//    for (var i=0; i<spl.length; i++) if (!spl[i].match(/^[a-zа-я_0-9]{0,2}$/)) 
//      words[words.length] = spl[i].toLowerCase();
//    return words.join(" ");
//  }
//};



//function addBlobInfo(blob_id, blobName, blob_code)
//{
////    var opts = 
////    {
////        'blob_id'      : blob_id
////        //,
////        //'field_text'
////    }
//    
//    blobSelector.instance();
////    {
////        var opts = 
////        {
////            'active'           : opts.active && true,
////            'blob_id'          : 1212,
////            'blob_code'        : '23er23f234f32f',
////            'field_text'       : 'какое-то сообщение',
////            'field_name'       : 'user_msg',
////            'insert_id'        : 'voice_msg_1'
////        }
//}



function simpleStorage ()
{
    var storage = new Object();
    
    this.add = function(val, id)
    {
        if (1 || typeof(storage[id]) == 'undefined')
        {
            storage[id] = val;
        }
    }
    
    this.get = function(id)
    {
        if (typeof(storage[id]) != 'undefined')
        {
            return storage[id];
        }
    }
    
    this.remove = function(id)
    {
        if (typeof(storage[id]) != 'undefined')
        {
            delete storage[id];
            return true;
        }
        return false;
    }
}

var blobSelector = new function()
{
    var curr = new Object();
    var selectors = new simpleStorage();
    
    this.getHTML = function (opts)
    {
        var content;
        var is_melody = ((typeof (opts.is_melody) != 'undefined' && opts.is_melody == 1) ? 1 : 0);
        
        if (is_melody)
        {
            if (typeof(opts.melody_id) != 'undefined' && opts.melody_id > 0)
            {
                var length = opts.field_text.length + 2;
                if (length > 40) length = 40;
                
                content =  '<table><tr>';
                content += '<td><input align="center" type="text" value="' + opts.field_text + '" size="' + length + '" readonly="true"/></td>';
                //content += '<td><a href="' + _pset.PATH_TO_ROOT + '/get_file.php?id=' + opts.blob_id + '&code=' + opts.blob_code + '"><img align="center" src="' + _pset.PATH_TO_IMG + '/save.gif" /></a></div>';
                content += '<td><a href="#" onclick="blobSelector.deleteVal(\'' + opts.insert_id + '\'); return false;"><img align="center" src="' + _pset.PATH_TO_IMG + '/element_delete.png" /></a>';
                content += '<input type="hidden" name="' + opts.field_name + '" value="' + opts.melody_id + '"/></td>';
                content += '</tr></table>';
                return content;
            }
            else 
            {
                var url_act = '#';
                var img_save = _pset.PATH_TO_IMG + '/record.gif';
                
                //alert (opts.is_melody);
                var onclick = 'blobSelector.attachVoiceMsg(\'' + opts.insert_id + '\'' + (is_melody ? ', 1' : '') + '); return false;';
                var title_str = JSLocaleCore['choose_vmsg'];
                var field_text = JSLocaleCore['choose'];
    
                content =  '<table><tr>';
                content += '<td><input align="center" type="text" value="' + field_text + '" style="width:90px; margin-right: 5px;" readonly="true"/></td>';
                content += '<td><a href="' + url_act + '" onclick="' + onclick + '"><img src="' + img_save + '" title="' + title_str + '"/></a></td>';
                content += '</tr></table>';
                return content;
            }
        }
        else
        {
            if (typeof(opts.blob_id) != 'undefined' && opts.blob_id > 0)
            {
                var length = opts.field_text.length + 2;
                if (length > 40) length = 40;
                
                content =  '<table><tr>';
                content += '<td><input align="center" type="text" value="' + opts.field_text + '" size="' + length + '" readonly="true"/></td>';
                content += '<td><a href="' + _pset.PATH_TO_ROOT + '/get_file.php?id=' + opts.blob_id + '&code=' + opts.blob_code + '"><img align="center" src="' + _pset.PATH_TO_IMG + '/save.gif" /></a></div>';
                content += '<td><a href="#" onclick="blobSelector.deleteVal(\'' + opts.insert_id + '\'); return false;"><img align="center" src="' + _pset.PATH_TO_IMG + '/element_delete.png" /></a>';
                content += '<input type="hidden" name="' + opts.field_name + '" value="' + opts.blob_id + '"/></td>';
                content += '</tr></table>';
                return content;
            }
            else 
            {
                var url_act = '#';
                var img_save = _pset.PATH_TO_IMG + '/record.gif';
                
                //alert (opts.is_melody);
                var onclick = 'blobSelector.attachVoiceMsg(\'' + opts.insert_id + '\'' + (is_melody ? ', 1' : '') + '); return false;';
                var title_str = JSLocaleCore['choose_vmsg'];
                var field_text = JSLocaleCore['choose'];
    
                content =  '<table><tr>';
                content += '<td><input align="center" type="text" value="' + field_text + '" style="width:90px; margin-right: 5px;" readonly="true"/></td>';
                content += '<td><a href="' + url_act + '" onclick="' + onclick + '"><img src="' + img_save + '" title="' + title_str + '"/></a></td>';
                content += '</tr></table>';
                return content;
            }
        }
    }
    
    
    /**
     * Adds field 
     *
     */
    this.instance = function(opts)
    {
        //opts.active = opts.active && true;
        //opts.insert_id = typeof(opts.insert_id) == 'undefined' ? 'div_voice_msg_1' : opts.insert_id;
        
        curr.insert_id = opts.insert_id;
        selectors.add(opts, opts.insert_id);
        
        jElem = $('#' + opts.insert_id);
        //opts.active ? jElem.show() : jElem.hide();
        jElem.html(this.getHTML(opts));
    }
    
    this.deleteVal = function (insert_id)
    {
        jElem = $('#' + insert_id);
        var opts = selectors.get(insert_id);
        var new_opts = 
        {
//            'blob_id'          : opt.blob_id;
//            'blob_code'        : opt.blob_code;
//            'field_text'       : '',
            'field_name'       : opts.field_name,
            'insert_id'        : opts.insert_id
            //'is_melody'        : (typeof(pts.is_melody) == 'undefined' ?   
        }
        if (typeof(opts.is_melody) != 'undefined' && opts.is_melody == 1)
            new_opts.is_melody = 1;
        
        jElem.html(this.getHTML(new_opts));
    }
    
    this.addBlobInfo = function(id, textName, blob_code)
    {
        jElem = $('#' + curr.insert_id);
        var opts = selectors.get(curr.insert_id);
        if (typeof (opts.is_melody) != 'undefined' && opts.is_melody == 1)
        {
            var new_opts = 
            {
                'active'           : true,
                'is_melody'        : 1,
                'melody_id'        : id,
                'field_text'       : textName,
                'field_name'       : opts.field_name,
                'insert_id'        : opts.insert_id
            }
        }
        else
        {
            var new_opts = 
            {
                'active'           : true,
                'blob_id'          : id,
                'blob_code'        : blob_code,
                'field_text'       : textName,
                'field_name'       : opts.field_name,
                'insert_id'        : opts.insert_id
            }
        }
        jElem.html(this.getHTML(new_opts));
    }
    
    this.attachVoiceMsg = function(insert_id, is_melody) 
    { 
        curr.insert_id = insert_id;
        var url;
        if (typeof(is_melody) != 'undefined' && is_melody == 1)
        {
            url = _pset.PATH_TO_ROOT_SCRIPT + "/voice_messages_main?tpl=simple&single_tab=melody"; 
        }
        else
        {
            url = _pset.PATH_TO_ROOT_SCRIPT + "/voice_messages_main?tpl=simple&single_tab=attach_msg"; 
        }
        
        var winname = "comtube"; var twidth = 1000; var theight = 700; 
        open_window(url, twidth, theight, winname);
    }
}


stateHolder = new function()
{
    var states = {};
    
    this.set = function(id, val)
    {
        if (1)
        {
            states.id = val;
        }
    }
    
    this.get = function(id)
    {
        if (typeof(states.id) != 'undefined')
        {
            return states.id;
        }
    }
    
    this.have = function(id)
    {
        if (typeof(states.id) != 'undefined')
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
}







var left_menu_scroll;

function left_menu_init()
{
    function fill_menu()
    {
        var jMenuInner = $('#menu_inner');
        var html = '';
        for (var i = 1; i <= sizeof(_pset.left_menu); i++)
        {
            if (_pset.left_menu[i].numpos == _pset.left_menu_pos) continue;
            
            if (_pset.left_menu[i].class_name == 'icon_12') 
            {
                var inside_html = '<span class="day_name">' + _pset.calendar_date.day_name + '</span><span class="day_number">' + _pset.calendar_date.day_number + '</span><span class="month_name">' + _pset.calendar_date.month_name + '</span>' + '<span class="link">' + _pset.left_menu[i].header +  '</span>';
            } 
            else 
            {
                var inside_html =  "<span>" + _pset.left_menu[i].header + "</span>";
                //var inside_html =  "<span>" +  "</span>";
            }
            html += '<div class="icon"><a href="' + _pset.left_menu[i].href + '" class="' + _pset.left_menu[i].class_name + '">' + inside_html + '</a></div>';
        }
        jMenuInner.html(html);
    };
    
    fill_menu();
    
    left_menu_scroll = new left_menu_scroll_f();
}

var left_menu_scroll_f = function()
{
    var menu_icons = 3;
    var menu_icons_all = sizeof(_pset.left_menu) - 1;
    var icon_height = 120;
    var menu_height = icon_height * menu_icons;
    var control_block_offset =  0;
    var control_block_size = menu_height - 2 * control_block_offset;
    var start_step_to_turn = 2;
    
    var menu_by_step = 0;
    //var step_count = menu_icons_all - menu_icons;
    var step_count = menu_icons_all;
    
    var jMenuInner = $('#menu_inner');
    var jMenuRunner = $('#menu_runner');
    var jMenuOuter = $('#menu_outer');
    
    var jMenuLeftHref = $('#menu_inner_left_href');
    
    jMenuOuter.css('height', menu_height);
    jMenuRunner.show();
    var menu_offset = jMenuOuter.offset();
    
    var start = get_start_position();
    var first_draw = true;
    
    var jMenuLeft = $('#menu_inner_left');
    var jIcons = $('#menu_inner .icon a');
    var jIconsLights;
    var jPrevLight = false;
    var jCurrLight = false;
    var prevStep = false;
    
    function menu_left_fill()
    {
        var icon_off_height = 9;
        var offsetY = Math.round ( (control_block_size - (menu_icons_all - 1) * icon_off_height) / menu_icons_all);
        var html = '<div id="lights" style="width:9px; padding-left:45px; padding-top:' + control_block_offset + 'px;">';
        for (var i = 1; i <= sizeof(_pset.left_menu); i++)
        {
            if (_pset.left_menu[i].numpos == _pset.left_menu_pos) continue;
            
            html += '<img src="' + _pset.PATH_TO_IMG + '/light_off.png' + '" style="padding-bottom: ' + offsetY + 'px;" />'
        }
        html += '</div>';
        jMenuLeft.html(html);
        
        jIconsLights = $('#lights img');
        
    }
    
    menu_left_fill();
    
    function get_start_position()
    {
        var start = {};
        start.pageY = Math.round( (_pset.left_menu_pos / menu_icons_all) * control_block_size + control_block_offset + menu_offset.top);
        return start;
    }
    
    function get_step_by_position(pos)
    {
        //alert('pos = ' + step_count);
//        if (pos < (start_step_to_turn) * icon_height)  
//        {
//            
//            return start_step_to_turn;
//        }
//        else if (pos > (step_count - (start_step_to_turn)) * icon_height)
//        {
//            
//            return step_count - start_step_to_turn;
//        }
//        else
if (1)
        {
            return 1 + Math.floor( step_count * (pos - control_block_offset)/ control_block_size);
        }
    }
    
    function get_position_by_step(step)
    {
//        if (step < start_step_to_turn))
//        {
//            alert('dd');
//            return start_step_to_turn * icon_height;
//        }
//        else if (step > (step_count - start_step_to_turn))
//        {
//            alert('dd2');
//            return (step_count - start_step_to_turn) * icon_height;
//        }
//        else
if (1)
        {
            return Math.round( ( (step - 1) / step_count) * control_block_size + control_block_offset);
        }
    }
    
    this.mouseout = function ()
    {
        jIcons.css('background-position', '');
    }
    
    this.redraw_menu = function (event, by_nearest_step, parentEvent)
    {
        var eventY;
        var runnerPosition;
        
        if (typeof (parentEvent) != 'undefined')
        {
            eventY = parentEvent.layerY;
        }
        else
        {
            var coordsScreen = mousePageXY(event);
            eventY = coordsScreen.y - menu_offset.top;
        }
        
        if ( eventY >= control_block_offset && eventY <= (menu_height - control_block_offset) )
        {
            runnerPosition = eventY;
        }
        else if (eventY < control_block_offset)
        {
            runnerPosition = control_block_offset;
        }
        else
        {
            runnerPosition = menu_height - control_block_offset ;
        }
        
        var step = get_step_by_position(runnerPosition);
        //alert(step);
        if (menu_by_step || (typeof(by_nearest_step) != 'undefined' && by_nearest_step))
        {
            
            runnerPosition = get_position_by_step(step);
        }
        
        
        var icon_pos = step - 1;
        $(jIcons[icon_pos]).css('background-position', '-45px -225px');
//        $(jIcons[icon_pos - 1]).css('background-position', '-45px -45px');
//        $(jIcons[icon_pos + 1]).css('background-position', '-45px -45px');

        $(jIcons[icon_pos - 1]).css('background-position', '');
        $(jIcons[icon_pos + 1]).css('background-position', '');
        
        jCurrLight = $(jIconsLights[icon_pos]);
        
        if (prevStep && step != prevStep)
        {
            jCurrLight.attr( 'src', _pset.PATH_TO_IMG + '/light_bl.png');
                
            if (jPrevLight)
            {
                jPrevLight.attr( 'src', _pset.PATH_TO_IMG + '/light_off.png');
            }
            
            jPrevLight = jCurrLight;
        }
        else if (!prevStep)
        {
            //jCurrLight.attr( 'src', _pset.PATH_TO_IMG + '/light_bl.png');
        }
        
        
        var menu_relative_pos;
        if (step < _pset.left_menu_pos)
        {
            menu_relative_pos = step;
        }
        else
        {
            menu_relative_pos = step + 1;
        }
        
        jMenuLeftHref.attr('href', _pset.left_menu[menu_relative_pos].href);
        
        var innerPositionNoOffset = (menu_icons_all - menu_icons) * (runnerPosition - control_block_offset) / menu_icons;
        var innerPosition = - Math.round( innerPositionNoOffset * menu_height / control_block_size );
        
        var step_correction_offset = Math.round( ( (menu_icons_all - menu_icons) * icon_height) * runnerPosition/control_block_size)
        //innerPosition = innerPosition + step_correction_offset;
        var correct_up = Math.round( ( (menu_icons_all - menu_icons) * icon_height) * runnerPosition/control_block_size)
        //innerPosition = innerPosition + 100;
        
        //innerPosition = innerPosition + Math.round( (100/7) * step + 500/7 );
        innerPosition = innerPosition + Math.round( (40/3) * step + 90 );
        
        if (step < start_step_to_turn)
        {
            innerPosition = 0;
        }
        else if (step > (step_count - start_step_to_turn + 1))
        {
            innerPosition = - ((menu_icons_all - menu_icons) * icon_height);
        }
        else
        {
            
            //innerPosition += (1) * icon_height;
        
        }


        if (1)
        {
            var debug = 
            {
                'eventY'            : eventY,
                'runnerPosition'    : runnerPosition,
                'innerPosition'     : innerPosition,
                'step'              : step,
                'event.clientY'     : event.clientY,
                'event.pageY'       : event.pageY,
                'menu_offset.top'   : menu_offset.top,
                
                'step_count'        : step_count,
                'control_block_size': control_block_size,
                'step_correction_offset' : step_correction_offset
            }
            debug_data(debug);
            //debug_data(event);
        }
        
        prevStep = step;
        
        jMenuInner.css('top', innerPosition);
        jMenuRunner.css('top', runnerPosition);
    
    }
    
    if (first_draw)
    {
        this.redraw_menu(start, true);
    }
    else
    {
        this.redraw_menu(start);
    }
    
    first_draw = false; 
}


function debug_data(obj)
{
    var html = '';
    for (var i in obj)
    {
        html += '<br />' + i + ' = ' + obj[i];
    }
    $('#debug_block').html(html);
}


phoneChecker = function(phone)
{
    phone = trim(phone);
    
    //var err = {};
    //var RANGE_ERR = -1;
    
    this.f = {};
    
    this.f.standart = function()
    {
        //return /^[0-9]{1}[0-9\.,]+[0-9]{1}$/.test(phone);
        var check = /^[0-9]{7}[0-9\.,]*$/.test(phone);
        
        var lastSymbol = phone.substr(phone.length - 1, 1);
        // last symbol must be numeric
        if (check && /^[0-9]$/.test(lastSymbol) )
        {
            return true;
        }
        else
        {
//            if (/^[0-9\.,]+$/.test(phone))
//            {
//                err.err_code = RANGE_ERR; 
//                err.err_text = "Номер не может иметь длину, меньшую, чем 2 символа"
//            }
            
        }
        return false;
    }

    this.f.internalSip = function()
    {
        //return /^[0-9]{1}[0-9]*[x|X]?$/.test(phone);
        var check = /^[0-9]{1}[0-9]*[x|X]$/.test(phone);
        if (!check) check = /^[0-9]{6}$/.test(phone);
        return check;
    }
    
    this.f.externalSip = function()
    {
        var check_num_is_sip = /^(?:sip\:[a-zA-Z0-9!#$%&\'*+\/\=?^_`{|}~\-\.\,]+@[a-zA-Z0-9!#$%&\'*+\/\=?^_`{|}~\-\.\,]+)$/i.test(phone);
        return (check_num_is_sip && phone.length <= 64);
    }
    
    this.checkAll = function()
    {
        var size =  sizeof(this.f);
        for (var i in this.f)
        {
            r = this.f[i]();
            if (r) 
            {
                return ret;
            }
        }
        return false;
    }
    
    this.checkMinLength = function()
    {
        //alert(phone.length < 6);
        return (phone.length >= 6);
    }
    
    this.checkCellPhone = function()
    {
        var checkCellPhone = /^[0-9]{7,}$/.test(phone);
        return checkCellPhone;
    }
    
}

//var gui_obj = {};
//gui_obj.add_attachment = function($jBindElem)
//{
//    var block = '\
//        <div id="attachment-form" style="top: 129px; left: 20px; visibility: visible;"><form action="./" enctype="multipart/form-data" method="post" name="form">\
//        <input type="hidden" value="2972ee9bed86615b87e02504b81c5093" name="_token"/><div><input type="file" name="_attachments[]"/></div>\
//        <div class="hint">Максимальный размер файла 5,0 МБ</div>\
//        <div class="buttons"><input type="button" value="Закрыть" onclick="document.getElementById(\'attachment-form\').style.visibility=\'hidden\'" class="button"/> <input type="button" value="Загрузить" onclick="rcmail.command(\'send-attachment\', this.form)" class="button"/></div>\
//        </form>\
//        </div>';
//}


function tab_menu(id)
{
    var jElem = $('#' + id);
    if ($(jElem).is(':visible'))
    {
        $(jElem).slideUp();
    }
    else
    {
        //$(jElem).css('background-color', '#E8CF92');
        $(jElem).slideDown("slow");
    }
    return false;
}

var inner_window_opened_f = false;
function toggle_inner_window(id, headerText)
{
    var IDwin = 'CT_inline_window';
    if (typeof(headerText) == 'undefined') var headerText = false;
    var jSourceEl = $('#' + id);
    var jOuterWindow = $('#content_all_id');
    var jMainContentWindow = $('#content_all_id div.content');
    
    if (inner_window_opened_f)
    {
        jMainContentWindow.show();
        $('#' + IDwin).remove();
        inner_window_opened_f = false;
        return;
    }
    
    var html = '\
<table width="100%" class="CT_inline_window_inner">\
    <tr style="padding: 0px; height: 20px;">\
        <td><h1 style="color:green;">' + headerText + '</h1></td>\
        <td align="right"><a onclick="toggle_inner_window(); return false;" href="">Закрыть</a></td>\
        <td width="21px"/>\
    </tr>\
    <tr>\
        <td colspan="3"><div style="padding: 0pt 10px 10px; overflow: auto; height: 425px;">' + jSourceEl.html() + '</div></td>\
    </tr>\
</table>\
';
    var jDiv = $('<div id="' + IDwin + '" class="CT_inline_window_outer">' + html + '</div>');

    jMainContentWindow.hide();
    jOuterWindow.append(jDiv);
    inner_window_opened_f = true;
    return;
}

// toggle_inner_window('what_sip_is', 'IP телефония - это круто!');


function instanceSettingsForm(_s)
{
    function drawForm(_s)
    {
        $('#use_mailbox_' + _s.use_mailbox).attr({checked : true});
        $('#sendnotify_email_' + _s.sendnotify_email).attr({checked : true});
        $('#sendnotify_sms_' + _s.sendnotify_sms).attr({checked : true});
        $('#createattachment_' + _s.createattachment).attr({checked : true});
	    
	    if (_s.fivcegreeting_id == -1)
	    {
	        $('#play_greeting_1').attr({checked : true});
	        $('#blob_cell').hide();
	    }
        else
        {
	        $('#play_greeting_2').attr({checked : true});
	        $('#blob_cell').show();
            
            addBlobInfo(_s.fivcegreeting_id, _s.msg_descr, _s.code_blob);
        }
        
        var jEmail = $('#email_1');
        if (typeof(_s.email) != 'undefined' && trim(_s.email) != '')
        {
            jEmail.val(_s.email);
            removeFormSpecialFormatting(jEmail);
        }
        else
        {
            jEmail.val('');
            jEmail.focus();
            jEmail.blur();
        }
    }
    
    if (typeof(_s) != 'undefined')
    {
        drawForm(_s);
    }
    else
    {
        JsHttpRequest.query(
            _pset.PATH_TO_ROOT + '/backend.php',
    		{
    			'action'		         : 'sip_configure',
    			'get_settings'           : 1
    		},
    		function(result, errors)
    		{
    			if (typeof(result.settings) != 'undefined' && result.settings)
    			{
    			   drawForm(result.settings);
    			}
    		}, 
    		true
    	);
    }
}

var start_money;

if (_pset.cur_id == 1) start_money = 10;
if (_pset.cur_id == 2) start_money = 1;
if (_pset.cur_id == 4) start_money = 3;

var end_reg_title = JSCoreLocale['end_reg']['title'];
var end_reg_body = '<table height="200">\
<tr>\
	<td>'+JSCoreLocale['end_reg']['bonus']+_pset.currency+'</td>\
	<td align="center"><font color="green"><b>'+start_money+'</b></font></td>\
</tr>\
<tr>\
	<td>'+JSCoreLocale['end_reg']['sms']+'</td>\
	<td width="120" align="center"><img src="'+_pset.PATH_TO_IMG + '/status-ok.gif"/></td>\
</tr>\
<tr>\
	<td>'+JSCoreLocale['end_reg']['conf']+'</td>\
	<td align="center"><img src="'+_pset.PATH_TO_IMG + '/status-ok.gif"/></td>\
</tr>\
<tr>\
	<td>'+JSCoreLocale['end_reg']['fax']+'</td>\
	<td align="center"><img src="'+_pset.PATH_TO_IMG + '/status-ok.gif"/></td>\
</tr>\
<tr>\
	<td>'+JSCoreLocale['end_reg']['sip']+'</td>\
	<td align="center"><img src="'+_pset.PATH_TO_IMG + '/status-ok.gif"/></td>\
</tr>\
<tr>\
	<td>'+JSCoreLocale['end_reg']['post']+'</td>\
	<td align="center"><img src="'+_pset.PATH_TO_IMG + '/status-ok.gif"/></td>\
</tr>\
</table>';

//send sms confirm registration

function trySMSsend(login, phone, callback_function, callback_function_params)
{
	login = trim(login);
	phone = trim(phone);
	
    JsHttpRequest.query(
        _pset.PATH_TO_ROOT + '/backend.php',
        {
            'action'            : 'send_sms',
            'login'             : login,
            'phone'             : phone
        },
        
        function(result, errors)
        {  
            callback_function( result, callback_function_params);
            
        }, 
        true
    );
}

//ok or error hints

function JT_notify(elem, img_src, notify_txt, st_type){
 
	var img_id = "JT_img_"+elem.id;
	var jt_id = "JT_"+elem.id;
	var title="&nbsp;";
	
	var coord_elem = getBounds(elem);

	
	
	var clickElementy = coord_elem.top;
 	var clickElementx = coord_elem.left + coord_elem.width + 5;
 	
 	var table_width = 600;


 	if (_pset.LANGUAGE == 'he') 
 	{	
 		clickElementx = coord_elem.left - table_width;
 		
 	}
 	
  	var notify_img = '<img id="'+img_id+'" src="'+img_src+'"/>';
  	
  	if (typeof(notify_txt) == 'undefined') notify_txt = '';
  	if (typeof(st_type) == 'undefined') st_type = 'input';
  	
  	var txt_formatting;
  	if (st_type=='ok') txt_formatting = '<span style="color:green;">'+notify_txt+'</span>';
  	else if (st_type=='error') txt_formatting = '<span style="color:red;">'+notify_txt+'</span>';
  	else if (st_type=='note') txt_formatting = '<span style="color:orange; left:5px;">'+notify_txt+'</span>';
  	else txt_formatting = '<span style="color:black; left:5px;">'+notify_txt+'</span>';
  	
  	var bodyHtml = '<div id="'+jt_id+'"><table width="'+table_width+'px" border="0"><tr><td width="19px">'+ notify_img +'</td><td>'+ txt_formatting + '</td></tr></table></div>';		
  	
  	$("body").append(bodyHtml);//left side
   
    $('#'+jt_id).css({position: "absolute", left: clickElementx+"px", top: clickElementy+"px"});
	$('#'+jt_id).show();
}

//autocomplete lookup plug-in

/*
	to install lookup on form input element
	you need to initialize inputVector with this struscture:

	var inputVector = {
		'jEl_input': input_Element,
		'jEl_sug_id' : id_for_suggetions_element,
		'res_size' : size_of_result_vector (if not initialized default 10)
		'result_function': user function for get result. necessary callback
		
	};
	
	then call function
	
	lookup_installLookup(inputVector)
	
	also you need to create userfunction to get result
	
	-----------------------------------------------------------------
	gch: And where is the specification for 'result_function' ???


*/

function lookup_installLookup(inputVector)
{
	
	//alert('lookup_installLookup');
	
	var jEl_input = inputVector['jEl_input'];
		
	if (typeof(jEl_input.attr("name"))!='undefined')
	{

		var listTop = getBounds(jEl_input[0]).top + getBounds(jEl_input[0]).height;
		var listLeft =  getBounds(jEl_input[0]).left;
		if (typeof(inputVector['jEl_sug_id']) != 'undefined')
		{
            var jEl_sug_id = inputVector['jEl_sug_id'];
		}
		else
		{
		    var jEl_sug_id = ctRand.generateUniqueId();
		}
		
		var bodyHtml = '<div id="'+jEl_sug_id+'" style="position: absolute; top:'+listTop+'; left:'+listLeft+'; height: 0px; z-index:2; display: none;"></div>';		
	  	
	  	$("body").append(bodyHtml);
		
		var jEl_sug = $('#'+jEl_sug_id);
		
		$('body').bind('click', function () {jEl_sug.hide() } );
		
		var res_size = 10;
		
		if (typeof(inputVector['res_size'])!='undefined')
		{
			res_size = inputVector['res_size'];
		}
		

		var result_function = function() 
		{
			return {};
		};
		
		if (typeof(inputVector['result_function'])!='undefined')
		{
			
			result_function = inputVector['result_function'];
		}
	
		inputVector['jEl_input'].bind('keydown', function (event) { lookup_onElemKeyDown(event, $(this), jEl_sug, result_function, res_size) } );
	}

}

function lookup_onElemKeyDown(event, jEl, jEl_sug, result_function, res_size)
{
		
	if ((event.keyCode != 38) && (event.keyCode != 40) && (event.keyCode != 9) && (event.keyCode != 13))
	{
		if (jEl.val().length > -1)
		{
			addToRunStack(function () 
			{ 
				lookup_lookupFunction(jEl, jEl_sug, result_function, res_size)
				
			
			}, 'lookup_lookupFunction', 300);
			
		}
		else jEl_sug.hide();
	}
	
	if (event.keyCode == 38) 
		{
			
				lookup_moveSelect(-1, jEl_sug);
		}
		
		if (event.keyCode == 40) 
		{	

				lookup_moveSelect(1, jEl_sug);
		}	
		
		if (event.keyCode == 9) 
		{
			event.keyCode = 13;
		}
		
		if (event.keyCode == 13)
		{
				lookup_selectElement(jEl, jEl_sug);			
		}
}

function lookup_lookupFunction(jEl, jEl_sug, result_function, res_size)
{
	
	var callback_funct = function(res)
	{
		lookup_callbackLookupElements(res, jEl, jEl_sug, res_size);
	};
	
	result_function(jEl, jEl_sug, res_size, jEl.val(), callback_funct);
	
	
	
}

function lookup_callbackLookupElements(res, jEl, jEl_sug, res_size)
{
	var data = '';
	var jEl_sug_id = jEl_sug.attr("id");

	jEl_sug.html(null);
	
	if (typeof(res)!='undefined')
	{

		jEl_sug.show();
		var list_size = res.length;
		
		if (list_size > res_size) list_size = res_size;
		
		if (list_size > 0)
		{
			data+='<div style="border: 1px solid #aaa; cursor: pointer; position:absolute; background: #FFFFFF;"><table width="148px">';
			
			for (var i=0; i<list_size; i++)
			{

				data += '<tr><div class="'+jEl_sug_id+'_elems" id="'+jEl_sug_id+'_elem_'+i+'" pos="'+i+'" onmousemove="lookup_elemMouseMove('+i+', document.getElementById(\''+jEl_sug_id+'\'));">'+res[i]['city_name']+'</div></tr>';
								
			}
			data+='</table></div>';
			jEl_sug.html(data);
			
			for (var i=0; i<list_size; i++)
			{
				$('#'+jEl_sug_id+'_elem_'+i).bind('click', function () {  lookup_selectElement(jEl, jEl_sug) } );
			}
		}
		
	}
	
	
}

function lookup_elemMouseMove(i, El)
{
	var jEl_sug = $(El);
	var jEl_sug_id = jEl_sug.attr("id");
	
	var jEl = $('[id="'+jEl_sug_id+'_elem_'+i+'"]');
	var jEl_prev = $('[id="'+jEl_sug_id+'_elem_sel"]');
	var pos = -1;
	
	if (typeof(jEl_prev)!='undefined')
	{
		pos = jEl_prev.attr("pos");
		
		if (pos!=i)
		{
			jEl_prev.attr("id",jEl_sug_id+"_elem_"+pos);
			jEl_prev.css("background-color","#FFFFFF");
		}
		
	}
	
		jEl.attr("id",jEl_sug_id+"_elem_sel");
	
		
		jEl.css("background-color","#CCCCCC");

	
}
	
function lookup_moveSelect(step, jEl_sug)
{
	var jEl_sug_id = jEl_sug.attr("id");
	
	var cur = $('[id="'+jEl_sug_id+'_elem_sel"]').attr("pos");
	
	var new_cur = 0;
	
	if (typeof(cur) != 'undefined')  new_cur = (parseInt(cur)+step);
	
	if (new_cur < 0) new_cur = $('[class^="'+jEl_sug_id+'_elems"]').length - 1;
	if  (new_cur >= $('[class^="'+jEl_sug_id+'_elems"]').length) new_cur = 0;
	

	$('[id="'+jEl_sug_id+'_elem_'+new_cur+'"]').css("background-color", "#CCCCCC");
	
	$('[id="'+jEl_sug_id+'_elem_sel"]').css("background-color", "#FFFFFF");
	
	$('[id="'+jEl_sug_id+'_elem_sel"]').attr("id", jEl_sug_id+"_elem_"+cur);
	
	$('[id="'+jEl_sug_id+'_elem_'+new_cur+'"]').attr("id", jEl_sug_id+"_elem_sel");
	
}


function lookup_selectElement(jEl, jEl_sug) 
{
	var jEl_sug_id = jEl_sug.attr("id");
	
	//alert($('[id="list_city_sel"]').html());
	if ($('[id="'+jEl_sug_id+'_elem_sel"]').html())
		jEl.val($('[id="'+jEl_sug_id+'_elem_sel"]').html());
		
  	jEl_sug.hide();
}

/* show tarif details */
function sh_tarif_det(id)
{
    var el = document.getElementById(id);
    if(el.style.display == 'none') {
        $("#"+id).fadeIn("slow");
    } else {
        el.style.display = 'none';
    }
}

/* show about details */
function show_about_details(id)
{
    var el = document.getElementById(id);
    if(el.style.display == 'none') 
    {
        $("div[id^='about_detail_']").css('display', 'none');
        $("#"+id).fadeIn("slow");
    } else {
        el.style.display = 'none';
    }
}



var ctRand =
{
    generateUniqueId : function()
    {
        do
        {
            var id = this.getRand();
        }
        while ( $('#' + id).length );
        return id;
    },
    
    getRand : function(size)
    {
        if (typeof(size) == 'undefined')
        {
            var size = 10;
        }
        var alfabet = 'qwertyuiopasdfghjklzxcvbnm';
        var str = '';
        for (var i = 0; i < size; i++)
        {
            //str += alfabet[ this.rand(0, alfabet.length - 1) ];
            str += alfabet.substring( (this.rand(0, alfabet.length - 1)), 1);
        }
        return str;
    },
    
    rand : function(left, right)
    {
        return left + Math.round(Math.random() * (right - left)); 
    },
    
    test : function () {return 'test_funct' } 
}

function chooseLanguageWindow()
{
   
   var base_str = '<table class="choose_lang always_left_to_right" border="0">'+
  '<tr>'+
  '<td><a class="icon_en" href="#" onclick="setLanguage(\'en\'); return false;"><br/><br/></br></br></br>English</a></td>'+  
  '<td><a class="icon_es" href="#" onclick="setLanguage(\'es\'); return false;"><br/><br/></br></br></br>Español</a></td>'+
    
    '<td><a class="icon_he" href="#" onclick="setLanguage(\'he\'); return false;"><br/><br/></br></br></br>עברית</a></td>'+
    
 
  '</tr>' +
  '<tr>'+
    '<td><a class="icon_cn" href="#" onclick="setLanguage(\'cn\'); return false;"><br/><br/></br></br></br>中文</a></td>'+
    '<td><a class="icon_ru" href="#" onclick="setLanguage(\'ru\'); return false;"><br/><br/></br></br></br>Русский</a></td>'+
    '<td><a class="icon_it" href="#" onclick="setLanguage(\'it\'); return false;"><br/><br/></br></br></br>Italiano</a></td>'+
    
 
  '</tr>' +
  '</table>';
    
  var form_str = 
    '<div style="background-color: transparent;">'+
      '<table cellspacing="0" cellpadding="0" style="width:100%;" class="blackForm">'+
      '<tr><td class="cornerWhiteTopLeft"> </td><td> </td><td class="cornerWhiteTopRight"> </td></tr>'+
      '<tr><td> </td><td>'+
        '<table cellspacing="0" cellpadding="0" style="width:100%;" class="blackFormInnerS">'+
          '<tr>'+
            '<td style="background-color: #F0F0F0; padding: 2px 0 2px 5px;">'+
              '<table cellspacing="0" cellpadding="0" style="width:100%;"><tr><td style="font-size:20px;">'+WClocale.get('main','choose_lang','title')+'</td><td>'+
                '<img class="closeBtn_out right_to_left" src="' + _pset.PATH_TO_IMG + '/blank.gif" title="'+JSCoreLocale['close']+'" alt="'+JSCoreLocale['close']+'" onclick="$.unblockUI();"'+
                  'onmouseover="this.className=\'closeBtn_over right_to_left\'" onmouseout="this.className=\'closeBtn_out right_to_left\'"/>'+
              '</td></tr></table>'+
            '</td>'+
          '</tr>'+
          '<tr>'+
            '<td align="center" style="padding: 5px 0 5px 0;">'+ base_str +'</td>'+
          '</tr>'+
        '</table>'+
      '</td><td> </td></tr>'+
      '<tr><td class="cornerWhiteBottomLeft"> </td><td> </td><td class="cornerWhiteBottomRight"> </td></tr>'+
      '</table>'+
    '</div>';
  var width = 350;
  var height = 300;
  
  var left_pos = ($(window).width() - width)/2;
  var top_pos = ($(window).height() - height)*0.45;
  if (left_pos < 0)
    left_pos = 0;
  
  $.blockUI({ 
		message: $(form_str),
    css: {
      top:      top_pos,
      left:     left_pos,
      width:    width,
      border:   'none',
      opacity:  '1',
      backgroundColor: 'transparent'
    }
  });	
  $('.blockOverlay').attr('title',JSCoreLocale['close']).click($.unblockUI);

}

function setLanguage(lang)
{
    var sep = '?';
    var req_url = _pset.REQUEST_STRING;
  
    var str = req_url.replace(/(\?|&)+lang=[a-z]{2}/g, '');
    if (str.match(/\?/)) sep = '&';
    
    str += sep + "lang=" + lang;
 
    document.location.href = str;
}

function confirm_del_lang(question_txt, row, lang)
{
    if (lang =='he')
        return confirm('?'+question_txt);
    else
        return confirm(question_txt+' \''+row+'\'?');
}

function confirm_del_lang2(question_txt, row, lang)
{
    if (lang =='he')
        return confirm('?'+question_txt);
    else
        return confirm(question_txt+' '+row+'?');
}

function confirm_del_sms_lang(question_txt, row, lang)
{
    if (lang =='he')
        return confirm('?'+row+' '+question_txt);
    else
        return confirm(question_txt+' '+row+'?');
}
var _comtubeLoaderFx = {};
_comtubeLoaderFx.open_window = function (url, twidth, theight, win_name) 
{
    if (typeof(twidth) == 'undefined') var twidth = 300; 
    if (typeof(theight) == 'undefined') var theight = 280;
        
    if (typeof(win_name) == 'undefined')
        var win_name = 'window_name_' + parseInt(Math.random()*1000);
        
    var screenLeft = Math.floor(Math.abs((screen.availWidth - twidth) / 2));
    var screenTop = Math.floor(Math.abs((screen.availHeight - theight) / 2));
    var ua = navigator.userAgent.toLowerCase();
    var is_opera = /opera/.test(ua);
    if (is_opera) screenTop -= (screen.height - screen.availHeight);
    var win = window.open(url, win_name, 
	   'fullscreen=no, toolbar=no, scrollbars=no, directories=no, status=no, menubar=no, resizable=no, width=' + twidth + ', height=' + theight
	   + ', left=' + screenLeft + ', top=' + screenTop);
   
	win.focus();
	return win;
}

if (typeof(open_window) == 'undefined')
{
    open_window = _comtubeLoaderFx.open_window;
}

JSLocaleCore = WClocale.get("main");

_pset.phone_validation_err = 
{
    'SUCCESS'                   : 0,
    'IP_ADDRESS_FORBIDDEN'      : 1,
    'NOT_FOUND'                 : 2,
    'PIN_IS_NOT_ACTIVE'         : 3,
    'LOCKED_NUMBER_BW_LIST'     : 4,
    'WRONG_NUMBER'              : 5,
    'SERVICE_IS_NOT_ACTIVE'     : 6,
    'NOWAYOUT'                  : 7,
    'NO_RETAIL_PRICE'           : 8,
    'NO_WHOLESALE_PRICE'        : 9,
    'NOT_ENOUGH_DATA'           : 10,
    'NOT_ENOUGH_MONEY'          : 11,
    'BAD_ACCOUNT'               : 12,
    'LOCKED_NUMBER_STOP_PHONE'  : 13
}

var phone_input, call_button_image;

$(document).ready(function() 
{
    phone_input = document.getElementById('input_user_phone_1');
    call_button_image = document.getElementById('call_button_image');

    if (typeof(phone_input) != 'undefined' && phone_input != null)
    {
        phone_input.focus();
    }
    
    if (typeof(_pset.call_to) != 'undefined' && _pset.call_to)
    {
        OnCall(_pset.call_to);
    }
    
});

var canCall = new function()
{
    this._canCall = false;
    this.set = function (val)
    {
        this._canCall = val;
        if (val)
        {
            onCanCall();
        }
        else
        {
            onCantCall();    
        }
    }
    
    this.get = function ()
    {
        return this._canCall;
    }
    
    function onCanCall()
    {
        call_button_image.disabled = false;
        phone_input.disabled = false;
        document.getElementById('result').innerHTML = '';
        $('#make_new_call').hide();
    
    }
    
    function onCantCall()
    {
        call_button_image.disabled = true;
        phone_input.disabled = true;
        setTimeout ( function () { $('#make_new_call').fadeIn() }, 3000);
    }
}

function OnCall(call_to)
{
//    call_button_image.src = _pset.PATH_TO_IMG + '/disabled_button.gif';
//    call_button_image.style.cursor = 'default';
    if (call_button_image)
        call_button_image.disabled = true;
    
    if (typeof(call_to) != 'undefined' && trim(call_to))
        var phone_num = call_to;
    else
        var phone_num = document.getElementById('input_user_phone_1').value;
        
    var regPhone = new RegExp("^[0-9]{1}[0-9\.,]+[0-9]{1}$", "g");
    if (!regPhone.test(phone_num))
    {
        var reason = JSLocaleCore['wrong_number'];
        callme_message_alert(reason);
    }
    else
    {
    	JsHttpRequest.query(
    	     _pset.button.PATH_TO_CALLME_SCRIPT,
    		{
    			'fsnumber'			: phone_num,
    			'pin'               : _pset.button.pin,
    			'hash'              : _pset.button.hash,
    			'mode'              : 0
    		},
    		function(result, errors)
    		{	
    		    var err_types = _pset.phone_validation_err;
    		    var was_no_answer = (typeof(result) != 'undefined' && trim(result)) ? 0 : 1;
    		    if (typeof(result) != 'undefined' && trim(result) && result == err_types.SUCCESS) 
    			{
    				document.getElementById('result_success').innerHTML = '<b><font color="#40E040" size="+1">'+JSLocaleCore['wait_call']+'   +'+FilteredCallNumber+'.</font></b>';
    				document.getElementById('result').innerHTML = '<br>';
    				canCall.set(false);
    			} 
    			else 
    			{
    			    if (result == err_types.WRONG_NUMBER) 
    				    var reason = JSLocaleCore['button_errs']['wrong_number'];
    				    
    			    else if (result == err_types.NO_RETAIL_PRICE)
        			    var reason = JSLocaleCore['button_errs']['no_retail_price'];
        			     
    			    else if (result == err_types.NO_WHOLESALE_PRICE)
        			    var reason = JSLocaleCore['button_errs']['no_wholesale_price'];
        			     
    			    else if (result == err_types.NOWAYOUT)
        			    var reason = JSLocaleCore['button_errs']['nowayout'];
        			     
        			else if (result == err_types.LOCKED_NUMBER_BW_LIST || result == err_types.LOCKED_NUMBER_STOP_PHONE)
        			    var reason = JSLocaleCore['button_errs']['locked'];
        			
        			else if (result == err_types.PIN_IS_NOT_ACTIVE)
        			    var reason = JSLocaleCore['button_errs']['pin_not_active'];
        			
    			    else if (result == err_types.NOT_ENOUGH_MONEY)
        			    var reason = JSLocaleCore['button_errs']['not_enough_money']; 
        			    
    			    else if (was_no_answer)
    			        var reason = JSLocaleCore['button_errs']['noanswer']; 
    			         
                    else
        			    var reason = JSLocaleCore['button_errs']['no_service']; 
        			   
        			callme_message_alert(reason);
    			}
    		}, 
    		true
        );
    };
}

function callme_message_alert(reason)
{
    document.getElementById('result').innerHTML = '<font color="red">  +'+ FilteredCallNumber + '. ' + reason + '.</font>';
    var call_button_image = document.getElementById('call_button_image');
    
    if (call_button_image)
	    call_button_image.disabled = false;			    
//    call_button_image.src = _pset.PATH_TO_IMG + '/callbutton1.gif';
//    call_button_image.style.cursor = 'pointer';
    
}

function check_hit_enter(evt) 
{
	if (!evt) {
		var evt = window.event;
	}
    key = ( evt.keyCode || evt.charCode || evt.which );
    if ( key == 13 ) { 
        FilterCallNumber();
    } 
}


//install_ajax_validation('callme');
 
