/*
 * jQuery Form Plugin
 * version: 2.63 (29-JAN-2011)
 * @requires jQuery v1.3.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function(b){b.fn.ajaxSubmit=function(t){if(!this.length){a("ajaxSubmit: skipping submit process - no element selected");return this}if(typeof t=="function"){t={success:t}}var h=this.attr("action");var d=(typeof h==="string")?b.trim(h):"";if(d){d=(d.match(/^([^#]+)/)||[])[1]}d=d||window.location.href||"";t=b.extend(true,{url:d,type:this[0].getAttribute("method")||"GET",iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank"},t);var u={};this.trigger("form-pre-serialize",[this,t,u]);if(u.veto){a("ajaxSubmit: submit vetoed via form-pre-serialize trigger");return this}if(t.beforeSerialize&&t.beforeSerialize(this,t)===false){a("ajaxSubmit: submit aborted via beforeSerialize callback");return this}var f,p,m=this.formToArray(t.semantic);if(t.data){t.extraData=t.data;for(f in t.data){if(t.data[f] instanceof Array){for(var i in t.data[f]){m.push({name:f,value:t.data[f][i]})}}else{p=t.data[f];p=b.isFunction(p)?p():p;m.push({name:f,value:p})}}}if(t.beforeSubmit&&t.beforeSubmit(m,this,t)===false){a("ajaxSubmit: submit aborted via beforeSubmit callback");return this}this.trigger("form-submit-validate",[m,this,t,u]);if(u.veto){a("ajaxSubmit: submit vetoed via form-submit-validate trigger");return this}var c=b.param(m);if(t.type.toUpperCase()=="GET"){t.url+=(t.url.indexOf("?")>=0?"&":"?")+c;t.data=null}else{t.data=c}var s=this,l=[];if(t.resetForm){l.push(function(){s.resetForm()})}if(t.clearForm){l.push(function(){s.clearForm()})}if(!t.dataType&&t.target){var r=t.success||function(){};l.push(function(n){var k=t.replaceTarget?"replaceWith":"html";b(t.target)[k](n).each(r,arguments)})}else{if(t.success){l.push(t.success)}}t.success=function(w,n,x){var v=t.context||t;for(var q=0,k=l.length;q<k;q++){l[q].apply(v,[w,n,x||s,s])}};var g=b("input:file",this).length>0;var e="multipart/form-data";var j=(s.attr("enctype")==e||s.attr("encoding")==e);if(t.iframe!==false&&(g||t.iframe||j)){if(t.closeKeepAlive){b.get(t.closeKeepAlive,o)}else{o()}}else{b.ajax(t)}this.trigger("form-submit-notify",[this,t]);return this;function o(){var v=s[0];if(b(":input[name=submit],:input[id=submit]",v).length){alert('Error: Form elements must not have name or id of "submit".');return}var B=b.extend(true,{},b.ajaxSettings,t);B.context=B.context||B;var E="jqFormIO"+(new Date().getTime()),z="_"+E;var w=b('<iframe id="'+E+'" name="'+E+'" src="'+B.iframeSrc+'" />');var A=w[0];w.css({position:"absolute",top:"-1000px",left:"-1000px"});var x={aborted:0,responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(){this.aborted=1;w.attr("src",B.iframeSrc)}};var I=B.global;if(I&&!b.active++){b.event.trigger("ajaxStart")}if(I){b.event.trigger("ajaxSend",[x,B])}if(B.beforeSend&&B.beforeSend.call(B.context,x,B)===false){if(B.global){b.active--}return}if(x.aborted){return}var H=0;var y=v.clk;if(y){var F=y.name;if(F&&!y.disabled){B.extraData=B.extraData||{};B.extraData[F]=y.value;if(y.type=="image"){B.extraData[F+".x"]=v.clk_x;B.extraData[F+".y"]=v.clk_y}}}function G(){var O=s.attr("target"),M=s.attr("action");v.setAttribute("target",E);if(v.getAttribute("method")!="POST"){v.setAttribute("method","POST")}if(v.getAttribute("action")!=B.url){v.setAttribute("action",B.url)}if(!B.skipEncodingOverride){s.attr({encoding:"multipart/form-data",enctype:"multipart/form-data"})}if(B.timeout){setTimeout(function(){H=true;D()},B.timeout)}var N=[];try{if(B.extraData){for(var P in B.extraData){N.push(b('<input type="hidden" name="'+P+'" value="'+B.extraData[P]+'" />').appendTo(v)[0])}}w.appendTo("body");A.attachEvent?A.attachEvent("onload",D):A.addEventListener("load",D,false);v.submit()}finally{v.setAttribute("action",M);if(O){v.setAttribute("target",O)}else{s.removeAttr("target")}b(N).remove()}}if(B.forceSync){G()}else{setTimeout(G,10)}var K,L,J=50;function D(){L=A.contentWindow?A.contentWindow.document:A.contentDocument?A.contentDocument:A.document;if(!L||L.location.href==B.iframeSrc){return}A.detachEvent?A.detachEvent("onload",D):A.removeEventListener("load",D,false);var N=true;try{if(H){throw"timeout"}var R=B.dataType=="xml"||L.XMLDocument||b.isXMLDoc(L);a("isXml="+R);if(!R&&window.opera&&(L.body==null||L.body.innerHTML=="")){if(--J){a("requeing onLoad callback, DOM not available");setTimeout(D,250);return}}x.responseText=L.body?L.body.innerHTML:L.documentElement?L.documentElement.innerHTML:null;x.responseXML=L.XMLDocument?L.XMLDocument:L;x.getResponseHeader=function(T){var S={"content-type":B.dataType};return S[T]};var Q=/(json|script)/.test(B.dataType);if(Q||B.textarea){var M=L.getElementsByTagName("textarea")[0];if(M){x.responseText=M.value}else{if(Q){var P=L.getElementsByTagName("pre")[0];var n=L.getElementsByTagName("body")[0];if(P){x.responseText=P.textContent}else{if(n){x.responseText=n.innerHTML}}}}}else{if(B.dataType=="xml"&&!x.responseXML&&x.responseText!=null){x.responseXML=C(x.responseText)}}K=k(x,B.dataType,B)}catch(O){a("error caught:",O);N=false;x.error=O;B.error.call(B.context,x,"error",O);I&&b.event.trigger("ajaxError",[x,B,O])}if(x.aborted){a("upload aborted");N=false}if(N){B.success.call(B.context,K,"success",x);I&&b.event.trigger("ajaxSuccess",[x,B])}I&&b.event.trigger("ajaxComplete",[x,B]);if(I&&!--b.active){b.event.trigger("ajaxStop")}B.complete&&B.complete.call(B.context,x,N?"success":"error");setTimeout(function(){w.removeData("form-plugin-onload");w.remove();x.responseXML=null},100)}var C=b.parseXML||function(n,M){if(window.ActiveXObject){M=new ActiveXObject("Microsoft.XMLDOM");M.async="false";M.loadXML(n)}else{M=(new DOMParser()).parseFromString(n,"text/xml")}return(M&&M.documentElement&&M.documentElement.nodeName!="parsererror")?M:null};var q=b.parseJSON||function(n){return window["eval"]("("+n+")")};var k=function(Q,O,N){var M=Q.getResponseHeader("content-type")||"",n=O==="xml"||!O&&M.indexOf("xml")>=0,P=n?Q.responseXML:Q.responseText;if(n&&P.documentElement.nodeName==="parsererror"){b.error&&b.error("parsererror")}if(N&&N.dataFilter){P=N.dataFilter(P,O)}if(typeof P==="string"){if(O==="json"||!O&&M.indexOf("json")>=0){P=q(P)}else{if(O==="script"||!O&&M.indexOf("javascript")>=0){b.globalEval(P)}}}return P}}};b.fn.ajaxForm=function(c){if(this.length===0){var d={s:this.selector,c:this.context};if(!b.isReady&&d.s){a("DOM not ready, queuing ajaxForm");b(function(){b(d.s,d.c).ajaxForm(c)});return this}a("terminating; zero elements found by selector"+(b.isReady?"":" (DOM not ready)"));return this}return this.ajaxFormUnbind().bind("submit.form-plugin",function(f){if(!f.isDefaultPrevented()){f.preventDefault();b(this).ajaxSubmit(c)}}).bind("click.form-plugin",function(j){var i=j.target;var g=b(i);if(!(g.is(":submit,input:image"))){var f=g.closest(":submit");if(f.length==0){return}i=f[0]}var h=this;h.clk=i;if(i.type=="image"){if(j.offsetX!=undefined){h.clk_x=j.offsetX;h.clk_y=j.offsetY}else{if(typeof b.fn.offset=="function"){var k=g.offset();h.clk_x=j.pageX-k.left;h.clk_y=j.pageY-k.top}else{h.clk_x=j.pageX-i.offsetLeft;h.clk_y=j.pageY-i.offsetTop}}}setTimeout(function(){h.clk=h.clk_x=h.clk_y=null},100)})};b.fn.ajaxFormUnbind=function(){return this.unbind("submit.form-plugin click.form-plugin")};b.fn.formToArray=function(q){var p=[];if(this.length===0){return p}var d=this[0];var g=q?d.getElementsByTagName("*"):d.elements;if(!g){return p}var k,h,f,r,e,m,c;for(k=0,m=g.length;k<m;k++){e=g[k];f=e.name;if(!f){continue}if(q&&d.clk&&e.type=="image"){if(!e.disabled&&d.clk==e){p.push({name:f,value:b(e).val()});p.push({name:f+".x",value:d.clk_x},{name:f+".y",value:d.clk_y})}continue}r=b.fieldValue(e,true);if(r&&r.constructor==Array){for(h=0,c=r.length;h<c;h++){p.push({name:f,value:r[h]})}}else{if(r!==null&&typeof r!="undefined"){p.push({name:f,value:r})}}}if(!q&&d.clk){var l=b(d.clk),o=l[0];f=o.name;if(f&&!o.disabled&&o.type=="image"){p.push({name:f,value:l.val()});p.push({name:f+".x",value:d.clk_x},{name:f+".y",value:d.clk_y})}}return p};b.fn.formSerialize=function(c){return b.param(this.formToArray(c))};b.fn.fieldSerialize=function(d){var c=[];this.each(function(){var h=this.name;if(!h){return}var f=b.fieldValue(this,d);if(f&&f.constructor==Array){for(var g=0,e=f.length;g<e;g++){c.push({name:h,value:f[g]})}}else{if(f!==null&&typeof f!="undefined"){c.push({name:this.name,value:f})}}});return b.param(c)};b.fn.fieldValue=function(h){for(var g=[],e=0,c=this.length;e<c;e++){var f=this[e];var d=b.fieldValue(f,h);if(d===null||typeof d=="undefined"||(d.constructor==Array&&!d.length)){continue}d.constructor==Array?b.merge(g,d):g.push(d)}return g};b.fieldValue=function(c,j){var e=c.name,p=c.type,q=c.tagName.toLowerCase();if(j===undefined){j=true}if(j&&(!e||c.disabled||p=="reset"||p=="button"||(p=="checkbox"||p=="radio")&&!c.checked||(p=="submit"||p=="image")&&c.form&&c.form.clk!=c||q=="select"&&c.selectedIndex==-1)){return null}if(q=="select"){var k=c.selectedIndex;if(k<0){return null}var m=[],d=c.options;var g=(p=="select-one");var l=(g?k+1:d.length);for(var f=(g?k:0);f<l;f++){var h=d[f];if(h.selected){var o=h.value;if(!o){o=(h.attributes&&h.attributes.value&&!(h.attributes.value.specified))?h.text:h.value}if(g){return o}m.push(o)}}return m}return b(c).val()};b.fn.clearForm=function(){return this.each(function(){b("input,select,textarea",this).clearFields()})};b.fn.clearFields=b.fn.clearInputs=function(){return this.each(function(){var d=this.type,c=this.tagName.toLowerCase();if(d=="text"||d=="password"||c=="textarea"){this.value=""}else{if(d=="checkbox"||d=="radio"){this.checked=false}else{if(c=="select"){this.selectedIndex=-1}}}})};b.fn.resetForm=function(){return this.each(function(){if(typeof this.reset=="function"||(typeof this.reset=="object"&&!this.reset.nodeType)){this.reset()}})};b.fn.enable=function(c){if(c===undefined){c=true}return this.each(function(){this.disabled=!c})};b.fn.selected=function(c){if(c===undefined){c=true}return this.each(function(){var d=this.type;if(d=="checkbox"||d=="radio"){this.checked=c}else{if(this.tagName.toLowerCase()=="option"){var e=b(this).parent("select");if(c&&e[0]&&e[0].type=="select-one"){e.find("option").selected(false)}this.selected=c}}})};function a(){if(b.fn.ajaxSubmit.debug){var c="[jquery.form] "+Array.prototype.join.call(arguments,"");if(window.console&&window.console.log){window.console.log(c)}else{if(window.opera&&window.opera.postError){window.opera.postError(c)}}}}})(jQuery);;// ColorBox v1.3.19 - jQuery lightbox plugin
// (c) 2011 Jack Moore - jacklmoore.com
// License: http://www.opensource.org/licenses/mit-license.php
(function(a,b,c){function Z(c,d,e){var g=b.createElement(c);return d&&(g.id=f+d),e&&(g.style.cssText=e),a(g)}function $(a){var b=y.length,c=(Q+a)%b;return c<0?b+c:c}function _(a,b){return Math.round((/%/.test(a)?(b==="x"?z.width():z.height())/100:1)*parseInt(a,10))}function ba(a){return K.photo||/\.(gif|png|jpe?g|bmp|ico)((#|\?).*)?$/i.test(a)}function bb(){var b;K=a.extend({},a.data(P,e));for(b in K)a.isFunction(K[b])&&b.slice(0,2)!=="on"&&(K[b]=K[b].call(P));K.rel=K.rel||P.rel||"nofollow",K.href=K.href||a(P).attr("href"),K.title=K.title||P.title,typeof K.href=="string"&&(K.href=a.trim(K.href))}function bc(b,c){a.event.trigger(b),c&&c.call(P)}function bd(){var a,b=f+"Slideshow_",c="click."+f,d,e,g;K.slideshow&&y[1]?(d=function(){F.text(K.slideshowStop).unbind(c).bind(j,function(){if(K.loop||y[Q+1])a=setTimeout(W.next,K.slideshowSpeed)}).bind(i,function(){clearTimeout(a)}).one(c+" "+k,e),r.removeClass(b+"off").addClass(b+"on"),a=setTimeout(W.next,K.slideshowSpeed)},e=function(){clearTimeout(a),F.text(K.slideshowStart).unbind([j,i,k,c].join(" ")).one(c,function(){W.next(),d()}),r.removeClass(b+"on").addClass(b+"off")},K.slideshowAuto?d():e()):r.removeClass(b+"off "+b+"on")}function be(b){U||(P=b,bb(),y=a(P),Q=0,K.rel!=="nofollow"&&(y=a("."+g).filter(function(){var b=a.data(this,e).rel||this.rel;return b===K.rel}),Q=y.index(P),Q===-1&&(y=y.add(P),Q=y.length-1)),S||(S=T=!0,r.show(),K.returnFocus&&a(P).blur().one(l,function(){a(this).focus()}),q.css({opacity:+K.opacity,cursor:K.overlayClose?"pointer":"auto"}).show(),K.w=_(K.initialWidth,"x"),K.h=_(K.initialHeight,"y"),W.position(),o&&z.bind("resize."+p+" scroll."+p,function(){q.css({width:z.width(),height:z.height(),top:z.scrollTop(),left:z.scrollLeft()})}).trigger("resize."+p),bc(h,K.onOpen),J.add(D).hide(),I.html(K.close).show()),W.load(!0))}function bf(){!r&&b.body&&(Y=!1,z=a(c),r=Z(X).attr({id:e,"class":n?f+(o?"IE6":"IE"):""}).hide(),q=Z(X,"Overlay",o?"position:absolute":"").hide(),s=Z(X,"Wrapper"),t=Z(X,"Content").append(A=Z(X,"LoadedContent","width:0; height:0; overflow:hidden"),C=Z(X,"LoadingOverlay").add(Z(X,"LoadingGraphic")),D=Z(X,"Title"),E=Z(X,"Current"),G=Z(X,"Next"),H=Z(X,"Previous"),F=Z(X,"Slideshow").bind(h,bd),I=Z(X,"Close")),s.append(Z(X).append(Z(X,"TopLeft"),u=Z(X,"TopCenter"),Z(X,"TopRight")),Z(X,!1,"clear:left").append(v=Z(X,"MiddleLeft"),t,w=Z(X,"MiddleRight")),Z(X,!1,"clear:left").append(Z(X,"BottomLeft"),x=Z(X,"BottomCenter"),Z(X,"BottomRight"))).find("div div").css({"float":"left"}),B=Z(X,!1,"position:absolute; width:9999px; visibility:hidden; display:none"),J=G.add(H).add(E).add(F),a(b.body).append(q,r.append(s,B)))}function bg(){return r?(Y||(Y=!0,L=u.height()+x.height()+t.outerHeight(!0)-t.height(),M=v.width()+w.width()+t.outerWidth(!0)-t.width(),N=A.outerHeight(!0),O=A.outerWidth(!0),r.css({"padding-bottom":L,"padding-right":M}),G.click(function(){W.next()}),H.click(function(){W.prev()}),I.click(function(){W.close()}),q.click(function(){K.overlayClose&&W.close()}),a(b).bind("keydown."+f,function(a){var b=a.keyCode;S&&K.escKey&&b===27&&(a.preventDefault(),W.close()),S&&K.arrowKey&&y[1]&&(b===37?(a.preventDefault(),H.click()):b===39&&(a.preventDefault(),G.click()))}),a("."+g,b).live("click",function(a){a.which>1||a.shiftKey||a.altKey||a.metaKey||(a.preventDefault(),be(this))})),!0):!1}var d={transition:"elastic",speed:300,width:!1,initialWidth:"600",innerWidth:!1,maxWidth:!1,height:!1,initialHeight:"450",innerHeight:!1,maxHeight:!1,scalePhotos:!0,scrolling:!0,inline:!1,html:!1,iframe:!1,fastIframe:!0,photo:!1,href:!1,title:!1,rel:!1,opacity:.9,preloading:!0,current:"image {current} of {total}",previous:"previous",next:"next",close:"close",open:!1,returnFocus:!0,reposition:!0,loop:!0,slideshow:!1,slideshowAuto:!0,slideshowSpeed:2500,slideshowStart:"start slideshow",slideshowStop:"stop slideshow",onOpen:!1,onLoad:!1,onComplete:!1,onCleanup:!1,onClosed:!1,overlayClose:!0,escKey:!0,arrowKey:!0,top:!1,bottom:!1,left:!1,right:!1,fixed:!1,data:undefined},e="colorbox",f="cbox",g=f+"Element",h=f+"_open",i=f+"_load",j=f+"_complete",k=f+"_cleanup",l=f+"_closed",m=f+"_purge",n=!a.support.opacity&&!a.support.style,o=n&&!c.XMLHttpRequest,p=f+"_IE6",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X="div",Y;if(a.colorbox)return;a(bf),W=a.fn[e]=a[e]=function(b,c){var f=this;b=b||{},bf();if(bg()){if(!f[0]){if(f.selector)return f;f=a("<a/>"),b.open=!0}c&&(b.onComplete=c),f.each(function(){a.data(this,e,a.extend({},a.data(this,e)||d,b))}).addClass(g),(a.isFunction(b.open)&&b.open.call(f)||b.open)&&be(f[0])}return f},W.position=function(a,b){function i(a){u[0].style.width=x[0].style.width=t[0].style.width=a.style.width,t[0].style.height=v[0].style.height=w[0].style.height=a.style.height}var c=0,d=0,e=r.offset(),g=z.scrollTop(),h=z.scrollLeft();z.unbind("resize."+f),r.css({top:-9e4,left:-9e4}),K.fixed&&!o?(e.top-=g,e.left-=h,r.css({position:"fixed"})):(c=g,d=h,r.css({position:"absolute"})),K.right!==!1?d+=Math.max(z.width()-K.w-O-M-_(K.right,"x"),0):K.left!==!1?d+=_(K.left,"x"):d+=Math.round(Math.max(z.width()-K.w-O-M,0)/2),K.bottom!==!1?c+=Math.max(z.height()-K.h-N-L-_(K.bottom,"y"),0):K.top!==!1?c+=_(K.top,"y"):c+=Math.round(Math.max(z.height()-K.h-N-L,0)/2),r.css({top:e.top,left:e.left}),a=r.width()===K.w+O&&r.height()===K.h+N?0:a||0,s[0].style.width=s[0].style.height="9999px",r.dequeue().animate({width:K.w+O,height:K.h+N,top:c,left:d},{duration:a,complete:function(){i(this),T=!1,s[0].style.width=K.w+O+M+"px",s[0].style.height=K.h+N+L+"px",K.reposition&&setTimeout(function(){z.bind("resize."+f,W.position)},1),b&&b()},step:function(){i(this)}})},W.resize=function(a){S&&(a=a||{},a.width&&(K.w=_(a.width,"x")-O-M),a.innerWidth&&(K.w=_(a.innerWidth,"x")),A.css({width:K.w}),a.height&&(K.h=_(a.height,"y")-N-L),a.innerHeight&&(K.h=_(a.innerHeight,"y")),!a.innerHeight&&!a.height&&(A.css({height:"auto"}),K.h=A.height()),A.css({height:K.h}),W.position(K.transition==="none"?0:K.speed))},W.prep=function(b){function g(){return K.w=K.w||A.width(),K.w=K.mw&&K.mw<K.w?K.mw:K.w,K.w}function h(){return K.h=K.h||A.height(),K.h=K.mh&&K.mh<K.h?K.mh:K.h,K.h}if(!S)return;var c,d=K.transition==="none"?0:K.speed;A.remove(),A=Z(X,"LoadedContent").append(b),A.hide().appendTo(B.show()).css({width:g(),overflow:K.scrolling?"auto":"hidden"}).css({height:h()}).prependTo(t),B.hide(),a(R).css({"float":"none"}),o&&a("select").not(r.find("select")).filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one(k,function(){this.style.visibility="inherit"}),c=function(){function q(){n&&r[0].style.removeAttribute("filter")}var b,c,g=y.length,h,i="frameBorder",k="allowTransparency",l,o,p;if(!S)return;l=function(){clearTimeout(V),C.hide(),bc(j,K.onComplete)},n&&R&&A.fadeIn(100),D.html(K.title).add(A).show();if(g>1){typeof K.current=="string"&&E.html(K.current.replace("{current}",Q+1).replace("{total}",g)).show(),G[K.loop||Q<g-1?"show":"hide"]().html(K.next),H[K.loop||Q?"show":"hide"]().html(K.previous),K.slideshow&&F.show();if(K.preloading){b=[$(-1),$(1)];while(c=y[b.pop()])o=a.data(c,e).href||c.href,a.isFunction(o)&&(o=o.call(c)),ba(o)&&(p=new Image,p.src=o)}}else J.hide();K.iframe?(h=Z("iframe")[0],i in h&&(h[i]=0),k in h&&(h[k]="true"),h.name=f+ +(new Date),K.fastIframe?l():a(h).one("load",l),h.src=K.href,K.scrolling||(h.scrolling="no"),a(h).addClass(f+"Iframe").appendTo(A).one(m,function(){h.src="//about:blank"})):l(),K.transition==="fade"?r.fadeTo(d,1,q):q()},K.transition==="fade"?r.fadeTo(d,0,function(){W.position(0,c)}):W.position(d,c)},W.load=function(b){var c,d,e=W.prep;T=!0,R=!1,P=y[Q],b||bb(),bc(m),bc(i,K.onLoad),K.h=K.height?_(K.height,"y")-N-L:K.innerHeight&&_(K.innerHeight,"y"),K.w=K.width?_(K.width,"x")-O-M:K.innerWidth&&_(K.innerWidth,"x"),K.mw=K.w,K.mh=K.h,K.maxWidth&&(K.mw=_(K.maxWidth,"x")-O-M,K.mw=K.w&&K.w<K.mw?K.w:K.mw),K.maxHeight&&(K.mh=_(K.maxHeight,"y")-N-L,K.mh=K.h&&K.h<K.mh?K.h:K.mh),c=K.href,V=setTimeout(function(){C.show()},100),K.inline?(Z(X).hide().insertBefore(a(c)[0]).one(m,function(){a(this).replaceWith(A.children())}),e(a(c))):K.iframe?e(" "):K.html?e(K.html):ba(c)?(a(R=new Image).addClass(f+"Photo").error(function(){K.title=!1,e(Z(X,"Error").text("This image could not be loaded"))}).load(function(){var a;R.onload=null,K.scalePhotos&&(d=function(){R.height-=R.height*a,R.width-=R.width*a},K.mw&&R.width>K.mw&&(a=(R.width-K.mw)/R.width,d()),K.mh&&R.height>K.mh&&(a=(R.height-K.mh)/R.height,d())),K.h&&(R.style.marginTop=Math.max(K.h-R.height,0)/2+"px"),y[1]&&(K.loop||y[Q+1])&&(R.style.cursor="pointer",R.onclick=function(){W.next()}),n&&(R.style.msInterpolationMode="bicubic"),setTimeout(function(){e(R)},1)}),setTimeout(function(){R.src=c},1)):c&&B.load(c,K.data,function(b,c,d){e(c==="error"?Z(X,"Error").text("Request unsuccessful: "+d.statusText):a(this).contents())})},W.next=function(){!T&&y[1]&&(K.loop||y[Q+1])&&(Q=$(1),W.load())},W.prev=function(){!T&&y[1]&&(K.loop||Q)&&(Q=$(-1),W.load())},W.close=function(){S&&!U&&(U=!0,S=!1,bc(k,K.onCleanup),z.unbind("."+f+" ."+p),q.fadeTo(200,0),r.stop().fadeTo(300,0,function(){r.add(q).css({opacity:1,cursor:"auto"}).hide(),bc(m),A.remove(),setTimeout(function(){U=!1,bc(l,K.onClosed)},1)}))},W.remove=function(){a([]).add(r).add(q).remove(),r=null,a("."+g).removeData(e).removeClass(g).die()},W.element=function(){return a(P)},W.settings=d})(jQuery,document,this);;/*
 * FancyBox - jQuery Plugin
 * Simple and fancy lightbox alternative
 *
 * Examples and documentation at: http://fancybox.net
 * 
 * Copyright (c) 2008 - 2010 Janis Skarnelis
 * That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated.
 * 
 * Version: 1.3.4 (11/11/2010)
 * Requires: jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

;(function(b){var m,t,u,f,D,j,E,n,z,A,q=0,e={},o=[],p=0,d={},l=[],G=null,v=new Image,J=/\.(jpg|gif|png|bmp|jpeg)(.*)?$/i,W=/[^\.]\.(swf)\s*$/i,K,L=1,y=0,s="",r,i,h=false,B=b.extend(b("<div/>")[0],{prop:0}),M=b.browser.msie&&b.browser.version<7&&!window.XMLHttpRequest,N=function(){t.hide();v.onerror=v.onload=null;G&&G.abort();m.empty()},O=function(){if(false===e.onError(o,q,e)){t.hide();h=false}else{e.titleShow=false;e.width="auto";e.height="auto";m.html('<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>');
F()}},I=function(){var a=o[q],c,g,k,C,P,w;N();e=b.extend({},b.fn.fancybox.defaults,typeof b(a).data("fancybox")=="undefined"?e:b(a).data("fancybox"));w=e.onStart(o,q,e);if(w===false)h=false;else{if(typeof w=="object")e=b.extend(e,w);k=e.title||(a.nodeName?b(a).attr("title"):a.title)||"";if(a.nodeName&&!e.orig)e.orig=b(a).children("img:first").length?b(a).children("img:first"):b(a);if(k===""&&e.orig&&e.titleFromAlt)k=e.orig.attr("alt");c=e.href||(a.nodeName?b(a).attr("href"):a.href)||null;if(/^(?:javascript)/i.test(c)||
c=="#")c=null;if(e.type){g=e.type;if(!c)c=e.content}else if(e.content)g="html";else if(c)g=c.match(J)?"image":c.match(W)?"swf":b(a).hasClass("iframe")?"iframe":c.indexOf("#")===0?"inline":"ajax";if(g){if(g=="inline"){a=c.substr(c.indexOf("#"));g=b(a).length>0?"inline":"ajax"}e.type=g;e.href=c;e.title=k;if(e.autoDimensions)if(e.type=="html"||e.type=="inline"||e.type=="ajax"){e.width="auto";e.height="auto"}else e.autoDimensions=false;if(e.modal){e.overlayShow=true;e.hideOnOverlayClick=false;e.hideOnContentClick=
false;e.enableEscapeButton=false;e.showCloseButton=false}e.padding=parseInt(e.padding,10);e.margin=parseInt(e.margin,10);m.css("padding",e.padding+e.margin);b(".fancybox-inline-tmp").unbind("fancybox-cancel").bind("fancybox-change",function(){b(this).replaceWith(j.children())});switch(g){case "html":m.html(e.content);F();break;case "inline":if(b(a).parent().is("#fancybox-content")===true){h=false;break}b('<div class="fancybox-inline-tmp" />').hide().insertBefore(b(a)).bind("fancybox-cleanup",function(){b(this).replaceWith(j.children())}).bind("fancybox-cancel",
function(){b(this).replaceWith(m.children())});b(a).appendTo(m);F();break;case "image":h=false;b.fancybox.showActivity();v=new Image;v.onerror=function(){O()};v.onload=function(){h=true;v.onerror=v.onload=null;e.width=v.width;e.height=v.height;b("<img />").attr({id:"fancybox-img",src:v.src,alt:e.title}).appendTo(m);Q()};v.src=c;break;case "swf":e.scrolling="no";C='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+e.width+'" height="'+e.height+'"><param name="movie" value="'+c+
'"></param>';P="";b.each(e.swf,function(x,H){C+='<param name="'+x+'" value="'+H+'"></param>';P+=" "+x+'="'+H+'"'});C+='<embed src="'+c+'" type="application/x-shockwave-flash" width="'+e.width+'" height="'+e.height+'"'+P+"></embed></object>";m.html(C);F();break;case "ajax":h=false;b.fancybox.showActivity();e.ajax.win=e.ajax.success;G=b.ajax(b.extend({},e.ajax,{url:c,data:e.ajax.data||{},error:function(x){x.status>0&&O()},success:function(x,H,R){if((typeof R=="object"?R:G).status==200){if(typeof e.ajax.win==
"function"){w=e.ajax.win(c,x,H,R);if(w===false){t.hide();return}else if(typeof w=="string"||typeof w=="object")x=w}m.html(x);F()}}}));break;case "iframe":Q()}}else O()}},F=function(){var a=e.width,c=e.height;a=a.toString().indexOf("%")>-1?parseInt((b(window).width()-e.margin*2)*parseFloat(a)/100,10)+"px":a=="auto"?"auto":a+"px";c=c.toString().indexOf("%")>-1?parseInt((b(window).height()-e.margin*2)*parseFloat(c)/100,10)+"px":c=="auto"?"auto":c+"px";m.wrapInner('<div style="width:'+a+";height:"+c+
";overflow: "+(e.scrolling=="auto"?"auto":e.scrolling=="yes"?"scroll":"hidden")+';position:relative;"></div>');e.width=m.width();e.height=m.height();Q()},Q=function(){var a,c;t.hide();if(f.is(":visible")&&false===d.onCleanup(l,p,d)){b.event.trigger("fancybox-cancel");h=false}else{h=true;b(j.add(u)).unbind();b(window).unbind("resize.fb scroll.fb");b(document).unbind("keydown.fb");f.is(":visible")&&d.titlePosition!=="outside"&&f.css("height",f.height());l=o;p=q;d=e;if(d.overlayShow){u.css({"background-color":d.overlayColor,
opacity:d.overlayOpacity,cursor:d.hideOnOverlayClick?"pointer":"auto",height:b(document).height()});if(!u.is(":visible")){M&&b("select:not(#fancybox-tmp select)").filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one("fancybox-cleanup",function(){this.style.visibility="inherit"});u.show()}}else u.hide();i=X();s=d.title||"";y=0;n.empty().removeAttr("style").removeClass();if(d.titleShow!==false){if(b.isFunction(d.titleFormat))a=d.titleFormat(s,l,p,d);else a=s&&s.length?
d.titlePosition=="float"?'<table id="fancybox-title-float-wrap" cellpadding="0" cellspacing="0"><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">'+s+'</td><td id="fancybox-title-float-right"></td></tr></table>':'<div id="fancybox-title-'+d.titlePosition+'">'+s+"</div>":false;s=a;if(!(!s||s==="")){n.addClass("fancybox-title-"+d.titlePosition).html(s).appendTo("body").show();switch(d.titlePosition){case "inside":n.css({width:i.width-d.padding*2,marginLeft:d.padding,marginRight:d.padding});
y=n.outerHeight(true);n.appendTo(D);i.height+=y;break;case "over":n.css({marginLeft:d.padding,width:i.width-d.padding*2,bottom:d.padding}).appendTo(D);break;case "float":n.css("left",parseInt((n.width()-i.width-40)/2,10)*-1).appendTo(f);break;default:n.css({width:i.width-d.padding*2,paddingLeft:d.padding,paddingRight:d.padding}).appendTo(f)}}}n.hide();if(f.is(":visible")){b(E.add(z).add(A)).hide();a=f.position();r={top:a.top,left:a.left,width:f.width(),height:f.height()};c=r.width==i.width&&r.height==
i.height;j.fadeTo(d.changeFade,0.3,function(){var g=function(){j.html(m.contents()).fadeTo(d.changeFade,1,S)};b.event.trigger("fancybox-change");j.empty().removeAttr("filter").css({"border-width":d.padding,width:i.width-d.padding*2,height:e.autoDimensions?"auto":i.height-y-d.padding*2});if(c)g();else{B.prop=0;b(B).animate({prop:1},{duration:d.changeSpeed,easing:d.easingChange,step:T,complete:g})}})}else{f.removeAttr("style");j.css("border-width",d.padding);if(d.transitionIn=="elastic"){r=V();j.html(m.contents());
f.show();if(d.opacity)i.opacity=0;B.prop=0;b(B).animate({prop:1},{duration:d.speedIn,easing:d.easingIn,step:T,complete:S})}else{d.titlePosition=="inside"&&y>0&&n.show();j.css({width:i.width-d.padding*2,height:e.autoDimensions?"auto":i.height-y-d.padding*2}).html(m.contents());f.css(i).fadeIn(d.transitionIn=="none"?0:d.speedIn,S)}}}},Y=function(){if(d.enableEscapeButton||d.enableKeyboardNav)b(document).bind("keydown.fb",function(a){if(a.keyCode==27&&d.enableEscapeButton){a.preventDefault();b.fancybox.close()}else if((a.keyCode==
37||a.keyCode==39)&&d.enableKeyboardNav&&a.target.tagName!=="INPUT"&&a.target.tagName!=="TEXTAREA"&&a.target.tagName!=="SELECT"){a.preventDefault();b.fancybox[a.keyCode==37?"prev":"next"]()}});if(d.showNavArrows){if(d.cyclic&&l.length>1||p!==0)z.show();if(d.cyclic&&l.length>1||p!=l.length-1)A.show()}else{z.hide();A.hide()}},S=function(){if(!b.support.opacity){j.get(0).style.removeAttribute("filter");f.get(0).style.removeAttribute("filter")}e.autoDimensions&&j.css("height","auto");f.css("height","auto");
s&&s.length&&n.show();d.showCloseButton&&E.show();Y();d.hideOnContentClick&&j.bind("click",b.fancybox.close);d.hideOnOverlayClick&&u.bind("click",b.fancybox.close);b(window).bind("resize.fb",b.fancybox.resize);d.centerOnScroll&&b(window).bind("scroll.fb",b.fancybox.center);if(d.type=="iframe")b('<iframe id="fancybox-frame" name="fancybox-frame'+(new Date).getTime()+'" frameborder="0" hspace="0" '+(b.browser.msie?'allowtransparency="true""':"")+' scrolling="'+e.scrolling+'" src="'+d.href+'"></iframe>').appendTo(j);
f.show();h=false;b.fancybox.center();d.onComplete(l,p,d);var a,c;if(l.length-1>p){a=l[p+1].href;if(typeof a!=="undefined"&&a.match(J)){c=new Image;c.src=a}}if(p>0){a=l[p-1].href;if(typeof a!=="undefined"&&a.match(J)){c=new Image;c.src=a}}},T=function(a){var c={width:parseInt(r.width+(i.width-r.width)*a,10),height:parseInt(r.height+(i.height-r.height)*a,10),top:parseInt(r.top+(i.top-r.top)*a,10),left:parseInt(r.left+(i.left-r.left)*a,10)};if(typeof i.opacity!=="undefined")c.opacity=a<0.5?0.5:a;f.css(c);
j.css({width:c.width-d.padding*2,height:c.height-y*a-d.padding*2})},U=function(){return[b(window).width()-d.margin*2,b(window).height()-d.margin*2,b(document).scrollLeft()+d.margin,b(document).scrollTop()+d.margin]},X=function(){var a=U(),c={},g=d.autoScale,k=d.padding*2;c.width=d.width.toString().indexOf("%")>-1?parseInt(a[0]*parseFloat(d.width)/100,10):d.width+k;c.height=d.height.toString().indexOf("%")>-1?parseInt(a[1]*parseFloat(d.height)/100,10):d.height+k;if(g&&(c.width>a[0]||c.height>a[1]))if(e.type==
"image"||e.type=="swf"){g=d.width/d.height;if(c.width>a[0]){c.width=a[0];c.height=parseInt((c.width-k)/g+k,10)}if(c.height>a[1]){c.height=a[1];c.width=parseInt((c.height-k)*g+k,10)}}else{c.width=Math.min(c.width,a[0]);c.height=Math.min(c.height,a[1])}c.top=parseInt(Math.max(a[3]-20,a[3]+(a[1]-c.height-40)*0.5),10);c.left=parseInt(Math.max(a[2]-20,a[2]+(a[0]-c.width-40)*0.5),10);return c},V=function(){var a=e.orig?b(e.orig):false,c={};if(a&&a.length){c=a.offset();c.top+=parseInt(a.css("paddingTop"),
10)||0;c.left+=parseInt(a.css("paddingLeft"),10)||0;c.top+=parseInt(a.css("border-top-width"),10)||0;c.left+=parseInt(a.css("border-left-width"),10)||0;c.width=a.width();c.height=a.height();c={width:c.width+d.padding*2,height:c.height+d.padding*2,top:c.top-d.padding-20,left:c.left-d.padding-20}}else{a=U();c={width:d.padding*2,height:d.padding*2,top:parseInt(a[3]+a[1]*0.5,10),left:parseInt(a[2]+a[0]*0.5,10)}}return c},Z=function(){if(t.is(":visible")){b("div",t).css("top",L*-40+"px");L=(L+1)%12}else clearInterval(K)};
b.fn.fancybox=function(a){if(!b(this).length)return this;b(this).data("fancybox",b.extend({},a,b.metadata?b(this).metadata():{})).unbind("click.fb").bind("click.fb",function(c){c.preventDefault();if(!h){h=true;b(this).blur();o=[];q=0;c=b(this).attr("rel")||"";if(!c||c==""||c==="nofollow")o.push(this);else{o=b("a[rel="+c+"], area[rel="+c+"]");q=o.index(this)}I()}});return this};b.fancybox=function(a,c){var g;if(!h){h=true;g=typeof c!=="undefined"?c:{};o=[];q=parseInt(g.index,10)||0;if(b.isArray(a)){for(var k=
0,C=a.length;k<C;k++)if(typeof a[k]=="object")b(a[k]).data("fancybox",b.extend({},g,a[k]));else a[k]=b({}).data("fancybox",b.extend({content:a[k]},g));o=jQuery.merge(o,a)}else{if(typeof a=="object")b(a).data("fancybox",b.extend({},g,a));else a=b({}).data("fancybox",b.extend({content:a},g));o.push(a)}if(q>o.length||q<0)q=0;I()}};b.fancybox.showActivity=function(){clearInterval(K);t.show();K=setInterval(Z,66)};b.fancybox.hideActivity=function(){t.hide()};b.fancybox.next=function(){return b.fancybox.pos(p+
1)};b.fancybox.prev=function(){return b.fancybox.pos(p-1)};b.fancybox.pos=function(a){if(!h){a=parseInt(a);o=l;if(a>-1&&a<l.length){q=a;I()}else if(d.cyclic&&l.length>1){q=a>=l.length?0:l.length-1;I()}}};b.fancybox.cancel=function(){if(!h){h=true;b.event.trigger("fancybox-cancel");N();e.onCancel(o,q,e);h=false}};b.fancybox.close=function(){function a(){u.fadeOut("fast");n.empty().hide();f.hide();b.event.trigger("fancybox-cleanup");j.empty();d.onClosed(l,p,d);l=e=[];p=q=0;d=e={};h=false}if(!(h||f.is(":hidden"))){h=
true;if(d&&false===d.onCleanup(l,p,d))h=false;else{N();b(E.add(z).add(A)).hide();b(j.add(u)).unbind();b(window).unbind("resize.fb scroll.fb");b(document).unbind("keydown.fb");j.find("iframe").attr("src",M&&/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank");d.titlePosition!=="inside"&&n.empty();f.stop();if(d.transitionOut=="elastic"){r=V();var c=f.position();i={top:c.top,left:c.left,width:f.width(),height:f.height()};if(d.opacity)i.opacity=1;n.empty().hide();B.prop=1;
b(B).animate({prop:0},{duration:d.speedOut,easing:d.easingOut,step:T,complete:a})}else f.fadeOut(d.transitionOut=="none"?0:d.speedOut,a)}}};b.fancybox.resize=function(){u.is(":visible")&&u.css("height",b(document).height());b.fancybox.center(true)};b.fancybox.center=function(a){var c,g;if(!h){g=a===true?1:0;c=U();!g&&(f.width()>c[0]||f.height()>c[1])||f.stop().animate({top:parseInt(Math.max(c[3]-20,c[3]+(c[1]-j.height()-40)*0.5-d.padding)),left:parseInt(Math.max(c[2]-20,c[2]+(c[0]-j.width()-40)*0.5-
d.padding))},typeof a=="number"?a:200)}};b.fancybox.init=function(){if(!b("#fancybox-wrap").length){b("body").append(m=b('<div id="fancybox-tmp"></div>'),t=b('<div id="fancybox-loading"><div></div></div>'),u=b('<div id="fancybox-overlay"></div>'),f=b('<div id="fancybox-wrap"></div>'));D=b('<div id="fancybox-outer"></div>').append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>').appendTo(f);
D.append(j=b('<div id="fancybox-content"></div>'),E=b('<a id="fancybox-close"></a>'),n=b('<div id="fancybox-title"></div>'),z=b('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),A=b('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>'));E.click(b.fancybox.close);t.click(b.fancybox.cancel);z.click(function(a){a.preventDefault();b.fancybox.prev()});A.click(function(a){a.preventDefault();b.fancybox.next()});
b.fn.mousewheel&&f.bind("mousewheel.fb",function(a,c){if(h)a.preventDefault();else if(b(a.target).get(0).clientHeight==0||b(a.target).get(0).scrollHeight===b(a.target).get(0).clientHeight){a.preventDefault();b.fancybox[c>0?"prev":"next"]()}});b.support.opacity||f.addClass("fancybox-ie");if(M){t.addClass("fancybox-ie6");f.addClass("fancybox-ie6");b('<iframe id="fancybox-hide-sel-frame" src="'+(/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank")+'" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(D)}}};
b.fn.fancybox.defaults={padding:10,margin:40,opacity:false,modal:false,cyclic:false,scrolling:"auto",width:560,height:340,autoScale:true,autoDimensions:true,centerOnScroll:false,ajax:{},swf:{wmode:"transparent"},hideOnOverlayClick:true,hideOnContentClick:false,overlayShow:true,overlayOpacity:0.7,overlayColor:"#777",titleShow:true,titlePosition:"float",titleFormat:null,titleFromAlt:false,transitionIn:"fade",transitionOut:"fade",speedIn:300,speedOut:300,changeSpeed:300,changeFade:"fast",easingIn:"swing",
easingOut:"swing",showCloseButton:true,showNavArrows:true,enableEscapeButton:true,enableKeyboardNav:true,onStart:function(){},onCancel:function(){},onComplete:function(){},onCleanup:function(){},onClosed:function(){},onError:function(){}};b(document).ready(function(){b.fancybox.init()})})(jQuery);;function checkMenuFL(elemid){	
    $.fn.colorbox({
        width:"966px",
        inline:true,
        href:"#menufl_" + elemid,
        close: " ",
        open:true,
        onClosed:function(){
            $.fn.colorbox.init();
        }
    });
}
	
function showTypesMenu(){   
    $.fn.colorbox({
        width:"966px",
        inline:true,
        href:"#menu_types",
        close: " ",
        open:true,
        onClosed:function(){
            $.fn.colorbox.init();
        }
    });
}
    
function tabs() {
    $("ul.tabs").each(function() {
        $(this).find("li").each(function(i) {
            $(this).click(function(){
                $(this).addClass("current").siblings().removeClass("current")
                .parents("div.section").find("div.box").hide().end().find("div.box:eq("+i+")").fadeIn(150);
            });
        });
    });
    return false;
};
	
//Функция 
function nav(){
    $("div#nav ul li").click(function() {
        $(this).find("ul:first").show();
    });

    $("div#nav ul li ul").mouseleave(function() {
        $("div#nav ul li ul").hide();
    });

    $("div#nav ul li ul.submenu").hide();
};
	
/*	function page(){
		$("li.open_sub").click(function() {
			$("li.open_sub ul.sub_box").hide();	
			$(this).find(\'ul:first\').show();
		});
	
		$("li.open_sub ul.sub_box").hide();
	};	
*/	
function openGalleryPopup(url, height, width) 
{
    var galleryWidth = width || 1150;
    var leftPos = calculateXForCentredPopup(galleryWidth);
    var newWindow = window.open(
        url,
        "_blank",
        "resizable=yes,scrollbars=yes,location=yes,toolbar=yes,status=no,top=0,screenY=0,left="
        + leftPos
        + ",screenX="
        + leftPos
        + ",height="
        + height + ",width=" + galleryWidth);
    return false;
}

function calculateXForCentredPopup(popupWidth) 
{
    var leftPos = 0;
    if (screen.availWidth > popupWidth) {
        leftPos = Math.round((screen.availWidth - popupWidth) / 2);
    }
    return leftPos;
}		
	
//Слайдер для шмоток
function slide_items(){

    var slide_count=$('.zslide').size();
    var slide_width=$('.zslide').width();
    var display=500;

    var count_width_slides=slide_count*slide_width;
    $('div.zlenta').css({
        width:count_width_slides
    });
		
    $('.zslide_next').bind("click", function() {
        var str_i=$(this).attr('title');
        var cur_cadr=parseInt($(this).attr('title'));
        if(str_i=="") cur_cadr=1;
        var left_part = slide_width*cur_cadr;
        if(count_width_slides-left_part < display) {
            $(this).parents('#zslider').find('div.zlenta').animate({
                left:0
            });
            cur_cadr=cur_cadr+2;
        }
        else
            $(this).parents('#zslider').find('div.zlenta').animate({
                left:(-1)*slide_width*cur_cadr
                });
			
        if((cur_cadr+1)>=slide_count) $(this).attr('title', 1);
        else $(this).attr('title', cur_cadr+1);
        if((cur_cadr-3)<0)	$(this).parents('#zslider').find('.zslider_prev').attr('title', slide_count-1);
        else $(this).parents('#zslider').find('.zslider_prev').attr('title', cur_cadr-3);
        return false;
    });
    //click(function(){
    $('.zslide_prev').bind("click", function() {
        var str_i=$(this).attr('title');
        var cur_cadr = parseInt($(this).attr('title'));
        if(str_i=="") cur_cadr=slide_count-3;
        //$(this).attr('title', cur_cadr);
        $(this).parents('#zslider').find('div.zlenta').animate({
            left:(-1)*slide_width*cur_cadr
            });
        if((cur_cadr-1)<0)	$(this).attr('title', slide_count-3);
        else $(this).attr('title', cur_cadr-1);
        if((cur_cadr+1)>=slide_count) 	$(this).parents('#zslider').find('.zslider_next').attr('title', 0);
        else $(this).parents('#zslider').find('.zslider_next').attr('title', cur_cadr+1);
        return false;
    });
}
function setCookie(name, value, expiredays, path, domain, secure) 
{
    if (expiredays)
    {
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        var expires = exdate.toGMTString();
    }
    document.cookie = name + "=" + escape(value) +
    ((expiredays) ? "; expires=" + expires : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

function getCookie(name)
{
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ((!start)&&(name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    text = unescape(document.cookie.substring(len, end));
    return text;
}

function deleteCookie(name)
{
    document.cookie = name + '=zzz;expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
function block_open(id)
{
    $('#'+id).fadeIn('fast');
}	
function block_close(id)
{
    $('#'+id).fadeOut('fast');
}
function block_toggle(id)
{		
    if ($('#'+id).is(":hidden")){
        $('#toggle_link').html("&laquo; скрыть");
    }
    else{
        $('#toggle_link').html("подробнее &raquo;");
    }
    $('#'+id).slideToggle('fast');
}

function block_toggle_h(id)
{		
    if ($('#'+id).is(":hidden")){
        $('#toggle_link').css("display", "none");
    }
    else{
        $('#toggle_link').html("подробнее &raquo;");
    }
    $('#'+id).slideToggle('slow');
}
	
function actFlash()
{
    objects = document.getElementsByTagName("object");
    for (var i = 0; i < objects.length; i++)

    {
            objects[i].outerHTML = objects[i].outerHTML;
        }
}
	
function more_menu(){
    $("#more").click(function() {
        $("#more ul.more_addmenu").show();
    });

    $("#more ul.more_addmenu").mouseleave(function() {
        $(this).hide();
    });

    $("#more ul.more_addmenu").hide();
};
	
	
//draw shopping guide flash
	
function draw_clock (par) {
    var flash_data = new Array();
    flash_data['appear'] = new Array();
    flash_data['appear']['msie'] = '<object id="idflash" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="524" height="524" id="top" align="top"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="/views/swf/shopping.swf" /><param name="menu" value="false" /><param name="quality" value="high" /><param name="scale" value="exactfit" /><param name="salign" value="t" /><param name="wmode" value="transparent" /><param name="bgcolor" value="#ffffff" /><param name="FlashVars" value="photocateg_id='+par+'" /></object>';
    flash_data['appear']['noie'] = '<embed id="idflash1" src="/views/swf/shopping.swf" menu="false" quality="high" scale="exactfit" salign="t" wmode="transparent" width="524" height="524" name="top" align="top" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"  FlashVars="photocateg_id='+par+'"></embed>';
    if ( document.all ) document.writeln(flash_data['appear']['msie']);
    else document.writeln(flash_data['appear']['noie']);
}	
	
	
function showFanclubPostImage(id) {
    $.fn.colorbox({
        href:"#"+id,
        initialHeight: 300,
        inline:true,
        open:true
    });
}

function checkEnterKey(e) {
    var myevent, key;

    if (e) { // Gecko and Opera
        myevent = e;
        if (myevent.charCode) {
            key = myevent.charCode;
        } else {
            key = myevent.keyCode;
        }
    } else { // IE
        key = window.event.keyCode;
    }

    return ((key == 10) || (key == 13));
}

function adTextAction( url, callbackAfter ) {
    $.ajax({
        type: 'POST',
        url: url,
        complete: callbackAfter
    })
}

function dropSortOrder() {
    setCookie('sort_order',2,1);
    document.cookie = "sort_order=;expires=Thu, 01-Jan-1970 00:00:01 GMT;";
}

$(function(){
    $('.round_img img').each(function() {
        src = $(this).attr('src');
        $(this).parent().css( {
            'background-image': 'url("'+src+'")',
            'background-position': '50% 50%',
            'behavior': 'url("/views/less/PIE.htc")'
        });
        $(this).css('display', 'none');
    });
});

$(function() {
      $("i.changeLnk").each(function() {
        var target = '';
        if($(this).attr("target")) {
          target = " target='" + $(this).attr("target") + "'";
        }
        var rel = '';
        if($(this).attr("rel")) {
          rel = " rel='" + $(this).attr("rel") + "'";
        }
        var title = '';
        if($(this).attr("alt")) {
          title = " title='" + $(this).attr("alt") + "'";
        }
        var id = '';
        if($(this).attr("id")) {
          id = " id='" + $(this).attr("id") + "'";
        }
        var onclick = '';
        if($(this).attr("onclick")) {
          onclick = " onclick='" + $(this).attr("onclick") + "'";
        }
        var cl = 'iproc';
        if($(this).attr("class")) {
          cl = " class='" + cl + " " + $(this).attr("class") + "'";
        }
        var style = '';
        if($(this).attr("style")) {
          style += " style='" + $(this).attr("style") + "'";
        }
        $(this).replaceWith("<a  href='" + $(this).attr("title") + "'" + title + cl + onclick + id + rel + target + ">" +$(this).html()+ "</a>");
      });
});

;	function log_debug(message) {
/*		$.ajax
		({
			url: '/logs/debug',
			type: 'POST',
			data: {'message': message},
			dataType: 'json',
			async: true,
			success: function(data){},
			error: function(data){}
		});
*/	}

	function log_error(message) {
		$.ajax
		({
			url: '/ajax/logs/errors/',
			type: 'POST',
			data: {'message': message},
			dataType: 'json',
			async: true,
			success: function(data){},
			error: function(data){}
		});
	}

	var api_data = {
		'status': 0, // 0 - Выполненно, 1 - Выполняется, 2 - Идет авторизация, 3 - Авторизация пройденна
		'last_code': 0, // 0 - Выполнено успешно, 1,2,3,4 - Коды ошибок
		'name': '',
		'auth_present': 0, // Была выполнена авторизация
		'group': '',
		'url': '',
		'params': {},
		'callback': null,
        'redirect_url': null, // where to redirect after callback invoked
		'auth_closed_by_user': 0,
		'registration_closed_by_user': 0
	}

    var blankEmail = false;

	function execApi(group,name,params,funcCallback) {
		log_debug('execApi: '+group+'.'+name);

		api_data['status'] = 1; // Выполняется
		api_data['name'] = name;
		api_data['auth_present'] = 0;
		api_data['group'] = group;
		api_data['url'] = '/ajax/api/'+group+'/'+name+'/';
		api_data['params'] = params;

		addApiCallBack(funcCallback);

		api_data['auth_closed_by_user'] = 0;
		api_data['registration_closed_by_user'] = 0;

		sendApiQuery();
	}

	function callbackWithErrors(error,message) {
		// error:
		//	  1 - Ошибка запроса на сервер
		//	  2 - Полученны некорректные данные
		//	  3 - Прерванна пользователем
		//	  4 - Внутренняя ошибка
		//	  5 - Неправильный вызов функции
		//	  6 - Отказано в доступе

		api_data['status'] = 0; // Выполненно
		api_data['last_code'] = error;

		invokeCallback(1, api_data['auth_present'], error, message);
	}

	function errorSending(data)	{
		log_error('Errors(answer): ' + data.responseText);

		callbackWithErrors(1, data.responseText);
	}

	function sendApiQuery()	{
		$.ajax
		({
			url: api_data['url'],
			type: 'POST',
			data: api_data['params'],
			dataType: 'json',
			async: true,
			success: answerServer,
			error: errorSending
		});
	}

	function answerServer(answer) {
		answer.errors -= 0;

        log_debug('answerServer '  + answer.errors);
		switch (answer.errors) {
			case 0: // Операция выполнена
				api_data['status'] = 0; // Выполненно
				api_data['last_code'] = 0;
		        invokeCallback(0, api_data['auth_present'], answer.code, answer.data);
				break;
			case 1: // Требуется авторизация
				if (api_data['status'] != 1) {
					callbackWithErrors(4,'Неправильный статус при авторизации: ' + api_data['status']);
				} else if (api_data['auth_present']) {
				    callbackWithErrors(4,'Повторная авторизация: ' + api_data['status']);
				} else {
				    authorization();
				}
				break;
			case 2: // Функция не определена
				callbackWithErrors(5,'Функция '+api_data['name']+' не определена');
				break;
			case 3: // Неправильно заданы входные параметры
				callbackWithErrors(5,'Неправильно заданы входные параметры');
				break;
			case 4: // Отказано в доступе
				callbackWithErrors(6,'Отказано в доступе');
				break;
			default:
				callbackWithErrors(2,'Неизвестный код возврата: ' + answer.errors);
		}

	}

	function authorization() {
		log_debug('authorization');

		api_data['status'] = 2; // Идет авторизация
		api_data['auth_closed_by_user'] = 0;
        showSignupDialog(authCancel, 'login');
	}

	function registration() {
		log_debug('registration');

		api_data['registration_closed_by_user'] = 0;
        showSignupDialog(registrationCancel, 'registration');
	}

	function lostPassword() {
		log_debug('lostPassword');

		api_data['registration_closed_by_user'] = 0;
        showSignupDialog(registrationCancel, 'lost_password');
	}

    function showSignupDialog(onCancel, panelId) {
        $.fancybox({
            'scrolling'		: 'no',
            'titleShow'		: false,
            'onClosed'		: onCancel,
            'showCloseButton': true,
            'href': '#dlgAuthorization',
            'onComplete': function() {
                if (!(jQuery.browser.msie && jQuery.browser.version == '9.0'))
                    $('.cabinet_left, .cabinet_right, .cabinet_right li a').css('behavior', "url('/views/less/PIE.htc')");
                setTimeout(function() {$('.cab1 .next').triggerHandler('click'); }, 5000);
            },
            'onStart': function () {
                setActivePanel(panelId);
            }
        });
    }

	function authSuccessfully(answer) {
		log_debug('authSuccessfully');

		api_data['status'] = 3; // Авторизация пройденна
		api_data['auth_present'] = 1;

		api_data['auth_closed_by_user'] = 1;
		$.fancybox.close();

        onLoggedIn(answer);
	}

	function authCancel() {
		log_debug('authCancel '+ api_data['auth_closed_by_user']);

		if (!api_data['auth_closed_by_user']) {
			callbackWithErrors(3,'Прервано пользователем');
		}

		return true;
	}

	function authError(data) {
		log_error('authError: ' + data.responseText);

		api_data['auth_closed_by_user'] = 1;
		$.fancybox.close();

		callbackWithErrors(1,'authError');
	}

	function authIncorrect(errors) {
		log_debug('authIncorrect ' + errors);

		$("#errors_label").html(errors);
	}

	function authBreak(code) {
		log_debug('authBreak');

		api_data['auth_closed_by_user'] = 1;
		$.fancybox.close();

		callbackWithErrors(1,'authBreak: ' + code);
	}

	function authAnswer(answer) {
		log_debug('authAnswer ' + answer.errors);

		answer.errors -= 0;

		switch (answer.errors) {
			case 0:
			    viewerId = answer.user_id;
			    authSuccessfully(answer);
			    break;
			case 1:
            case 2:
            case 3:
            case 100:
			    authIncorrect(answer.data.message);
			    break;
			default:
			    authBreak(answer.errors);
		}
	}

	function authorizationSend() {
		email = $("#email").val();
		password = $("#password").val();

		log_debug('authorizationSend ' + email);

		$.ajax
		({
			url: '/users/authorization/',
			type: 'POST',
			data: {'email': email, 'password': password},
			dataType: 'json',
			async: false,
			success: authAnswer,
			error: authError
		});

		return true;
	}

	function lostPasswordSend() {
		var email = $("#lost_pass_email").val();

		log_debug('lostPasswordSend ' + email);

		$.ajax
		({
			url: '/users/lost_password/',
			type: 'POST',
			data: {'email': email },
			dataType: 'json',
			async: false,
			success: showLostPasswordSentPanel,
			error: authError
		});

		return true;
	}

	function registrationSuccessfully(answer) {
		log_debug('registrationSuccessfully');

		api_data['status'] = 3; // Авторизация пройденна
		api_data['auth_present'] = 1;

		api_data['registration_closed_by_user'] = 1;
		$.fancybox.close();

        onLoggedIn(answer);
	}

	function registrationUserInfo(answer) {
		log_debug('registrationUserInfo');

        setActivePanel('registration_user_info');
	}

	function registrationCancel() {
		log_debug('registrationCancel '+ api_data['registration_closed_by_user']);

		if (!api_data['registration_closed_by_user']) {
			callbackWithErrors(3,'Прервано пользователем');
		}

		return true;
	}

	function registrationError(data) {
		log_error('registrationError: ' + data.responseText);

		api_data['registration_closed_by_user'] = 1;
		$.fancybox.close();

		callbackWithErrors(1, 'registrationError');
	}

	function registrationIncorrect(message) {
                hideErrorMessages('registration');
                showErrorMessage('registration', message);
		log_debug('registrationIncorrect');
	}

	function registrationBreak(code) {
		log_debug('registrationBreak: ' + code);

		api_data['registration_closed_by_user'] = 1;
		$.fn.colorbox.close();

		callbackWithErrors(1,'registrationBreak: ' + code);
	}

	function registrationAnswer(answer) {
		answer.errors -= 0;

		log_debug('registrationAnswer ' + answer.errors);

        $('#registration_submit_link').css('visibility', 'visible');
		switch (answer.errors) {
			case 0:
			    registrationUserInfo(answer);
			    break;
			case 1:
			    registrationIncorrect(answer.data.email);
			    break;

			default:
			    registrationBreak(answer.errors);
		}
	}

	function registrationUserInfoAnswer(answer) {
		answer.errors -= 0;

		log_debug('registrationUserInfoAnswer ' + answer.errors);

        $('#registration_user_info_submit_link').css('visibility', 'visible');
		switch (answer.errors) {
			case 0:
			    registrationSuccessfully(answer);
			    break;
			case 1:
			    registrationIncorrect(answer.data.message);
			    break;

			default:
			    registrationBreak(answer.errors);
		}
	}

    function showLinkingDlg() {
        api_data['registration_closed_by_user'] = 0;
        _showLinkingDialog(accountLinkingFinished);
	}

    function _showLinkingDialog(callback) {
        $.fn.colorbox({
            href:'#dlgAccountsLinking',
            inline:true,
            open:true,
            overlayClose:false,
            onClosed:callback,
            onLoad: function(){
                $('#colorbox').css('z-index', '9999');
                $('#cboxOverlay').css('z-index', '9999');
            }
        });
    }

    function showLinkingError(message) {
        $("#welcome").css('display', 'none');
        $("#question").css('display', 'none');
        $("#error_msg").css('display', 'block');
        $("#error_msg_span").html(message);
    }

    function showLinkingQuestion() {
        $("#welcome").css('display', 'none');
        $("#question").css('display', 'block');
        $("#blankEmailForm").css('display', 'none');
    }

    function showLinkingForm() {
        $("#question").css('display', 'none');
        $("#linkingForm").css('display', 'block');
    }

    function showStolenEmailForm() {
        $("#question").css('display', 'none');
        $("#linkedByEmailForm").css('display', 'none');
        $("#stolenEmail").css('display', 'block');
    }

    function showBlankEmailForm() {
        $("#welcome").css('display', 'none');
        $("#question").css('display', 'none');
        $("#linkingForm").css('display', 'none');
        $("#linkedByEmailForm").css('display', 'none');
        $("#blankEmailForm").css('display', 'block');
    }

    function showIncorrectAccountMessage(message) {
        $("#account_linking_warning").css('display', 'block');
        $("#account_linking_warning").html(message);
    }

    function accountLinkingSend() {
        $("#account_linking_warning").css('display', 'none');

        var email = $("#link_email").val();
        var password = $("#link_password").val();

        log_debug('accountLinkingSend ' + email);

        $.ajax
        ({
            url: '/users/accounts_linking/',
            type: 'POST',
            data: {'email': email, 'password': password},
            dataType: 'json',
            async: true,
            success: accountLinkingAnswer,
            error: registrationError
        });
    }


    function accountEmailSend() {
        $("#account_linking_warning").css('display', 'none');

        var email = $("#blank_email").val();

        log_debug('accountEmailSend ' + email);

        $.ajax
        ({
            url: '/users/accounts_email/',
            type: 'POST',
            data: {'email': email},
            dataType: 'json',
            async: true,
            success: accountEmailAnswer,
            error: registrationError
        });
    }

    function accountEmailAnswer(answer) {
        answer.errors -= 0;

        log_debug('accountLinkingAnswer '+answer.errors);
        switch (answer.errors) {
            case 0:
            case 200:
                blankEmail = false;
                viewerId = answer.user_id;
                accountLinkingFinished(answer);
                break;
            case 201:
                viewerId = answer.user_id;
                showLinkingQuestion(answer);
                break;
            default:
                showIncorrectAccountMessage(answer.data);
                break;
        }
    }

    function accountsLinkedByEmail(email) {
        log_debug('accountLinkedByEmail ' + email);

        api_data['registration_closed_by_user'] = 0;
        showLinkedByEmailForm(email);
        _showLinkingDialog(accountLinkingFinished);
    }

    function accountsBlankEmail() {
        log_debug('accountBlankEmail ');

        api_data['registration_closed_by_user'] = 0;
        showBlankEmailForm();
        _showLinkingDialog(onLoggedIn);
    }

    function showLinkedByEmailForm(email) {
        $("#question").css('display', 'none');
        $("#welcome").css('display', 'none');
        $("#linkedByEmailForm").css('display', 'block');
        $("#foundEmail").html(email);
    }

    function accountLinkingAnswer(answer) {
        answer.errors -= 0;

        log_debug('accountLinkingAnswer '+answer.errors);
        switch (answer.errors) {
            case 0:
                viewerId = answer.user_id;
                accountLinkingFinished(answer);
                break;
            default:
                showIncorrectAccountMessage(answer.data);
                break;
        }
    }

    function accountLinkingFinished(answer) {
        if (blankEmail) {
            blankEmail = false;
            showBlankEmailForm();
            return;
        }
        if (api_data['redirect_url'] == null && viewerId > 0) {
            api_data['redirect_url'] = "/cabinet/" + viewerId + "/settings/welcome";
        }

        onLoggedIn(answer);
    }

    function socialRegistrationAnswer(answer) {
        answer.errors -= 0;

        log_debug('socialRegistrationAnswer '+answer.errors);

        var callback = null;
        switch (answer.errors) {
            case 200:
                viewerId = answer.user_id;
                callback = function () {
                    socialRegistrationSuccessfully(answer);
                };
                break;
            case 201:
                viewerId = answer.user_id;
                callback = showLinkingQuestion;
                break;
            case 106:
                viewerId = answer.user_id;
                callback = function () {
                    accountsLinkedByEmail(answer.email);
                };
                break;
            case 103:
                viewerId = answer.user_id;
                blankEmail = true;
                callback = function () {
                    showLinkingQuestion();
                };
                break;
            case 202:
                registrationIncorrect(answer.data);
                friendsInfoSender = null;
                break;

            default:
                registrationBreak(answer.errors);
                friendsInfoSender = null;
        }
        if (friendsInfoSender != null) {
            friendsInfoSender.send(callback);
        } else if (callback != null) {
            callback();
        }
    }

    function socialRegistrationSuccessfully(answer) {
        log_debug('socialRegistrationSuccessfully');

        api_data['status'] = 3; // Авторизация пройденна
        api_data['auth_present'] = 1;

        api_data['registration_closed_by_user'] = 1;
        $.fn.colorbox.close();

        onLoggedIn(answer);
    }

    function onLoggedIn(answer) {
        if (api_data['redirect_url'] == null) {
            api_data['redirect_url'] = window.location + '';
        }
        if (api_data['url']) {
            sendApiQuery();
        } else {
            invokeCallback(0, api_data['auth_present'],
                    answer ? answer.code : null, answer ? answer.data : null);
        }
    }

    var friendsInfoSender;

    function socialRegistrationSend(userInfo) {
        log_debug('socialRegistrationSend');

        if (userInfo.error) {
            socialRegistrationError(userInfo.error);
            return;
        }
        var uid = userInfo.user.id;
        var netId = userInfo.user.netId;

        friendsInfoSender = new SocialFriendsSender(uid, netId, userInfo.friends, false);

        var location = "" + window.location;
        $.ajax
	    ({
	        url: '/users/social_signup/',
	        type: 'POST',
            data: {'user_info': $.toJSON(userInfo.user),
	               'uid': uid,
	               'net_id': netId,
	               'from_location' : location},
	        dataType: 'json',
	        success: socialRegistrationAnswer,
	        error: socialRegistrationError
	    });
	}

    function socialRegistrationError(data) {
        log_error('social registration Error: ' + data.message);
        showLinkingError(data.message);
    }

    function socialAccountsConnectSend(userInfo) {
        var uid = userInfo.user.id;
        var netId = userInfo.user.netId;

        friendsInfoSender = new SocialFriendsSender(uid, netId, userInfo.friends, true);

        $.ajax
        ({
            url: '/users/social_accounts_connect/',
            type: 'POST',
            data: {'user_info': $.toJSON(userInfo.user),
                   'uid': uid,
                   'net_id': netId},
            dataType: 'json',
            success: socialAccountsConnectAnswer,
            error: socialAccountsConnectAnswer
        });
    }

    function socialAccountsConnectAnswer(answer) {
        answer.errors -= 0;

        log_debug('socialFriendsConnectAnswer '+answer.errors);

        var msg = '';
        var netId = 0;
        var link = null;
        switch (answer.errors) {
            case 300:
                msg = "Ваши друзья из этой социальной сети уже подключены или ваши настройки безопасности в этой сети не позволяют получить доступ к друзьям.";
                netId = answer.net_id;
                friendsInfoSender = null;
                break;
            case 301:
                msg = "Аккаунт этой социальной сети уже подключен другим пользователем.";
                netId = answer.net_id;
                friendsInfoSender = null;
                break;
            case 0:
            default:
                netId = answer.net_id;
                link = answer.link;
                msg = answer.errors;
                break;
        }
        var callback = function () {
            var html = friendsInfoSender != null ? friendsInfoSender.getHtml() : '';
            showFoundFriends(html, msg, netId, link);
        };
        if (friendsInfoSender != null) {
            friendsInfoSender.send(callback);
        } else if (callback != null) {
            callback();
        }
    }

    function invokeCallback(errors, auth, code, data) {
        if (api_data['callback'] == null || api_data['callback'].length == 0) {
            apiFinalRedirect();
            return;
        }
        callback = api_data['callback'].shift();
        if (callback != null) {
            callback(errors, auth, code, data);
        }
        invokeCallback(errors, auth, code, data);
    }

    function addApiCallBack(callback) {
        if (callback == null) {
            return;
        }
        if (api_data['callback'] == null) {
            api_data['callback'] = [];
        }
        api_data['callback'].push(callback);
    }

    function setApiRedirectUrl(url) {
        api_data['redirect_url'] = url;
    }

    function getApiRedirectUrl() {
        return api_data['redirect_url'];
    }

    function apiFinalRedirect() {
        if (api_data['redirect_url'] == null) {
            return;
        }
        var location = api_data['redirect_url'];
        if (location != (window.location + '')) {
            window.location = api_data['redirect_url'];
        } else {
            window.location.reload();
        }
    }

    function SocialFriendsSender(uid, netId, friendsInfo, needHtml) {
        var NUM_AT_ONCE = 20;

        this.friendsInfo = friendsInfo;
        this.uid = uid;
        this.netId = netId;
        this.needHtml = needHtml;
        this.html = '';

        var me = this;

        this.callback = null;
        this.firstUnsentIndex = 0;
        this.numFriendsSent = 0;

        this.send = function(callback) {
            this.callback = callback;
            this.doSend();
        }

        this.doSend = function () {
            var startIndex = me.firstUnsentIndex;
            var endIndex = Math.min(startIndex + NUM_AT_ONCE, me.friendsInfo.length);

            var sendingInfo = me.friendsInfo.slice(startIndex, endIndex);
            var numSending = sendingInfo.length;
            $.ajax
            ({
                url: '/users/add_social_friends/',
                type: 'POST',
                data: {'uid': me.uid,
                       'net_id': me.netId,
                       'num_friends' : numSending,
                       'need_html' : me.needHtml,
                       'friends_info' : $.toJSON(sendingInfo)},
                dataType: 'json',
                success: me.sendAnswer,
                error: me.sendAnswer
            });
        }

        this.increaseUnsentIndex = function(increment) {
            this.firstUnsentIndex += increment;
        }

        this.increaseSentNumber = function(increment) {
            this.numFriendsSent += increment;
        }

        this.needToSendMore = function() {
            return this.firstUnsentIndex != this.friendsInfo.length;
        }

        this.sendAnswer = function (answer) {
            me.html += answer.html;
            me.increaseSentNumber(parseInt(answer.numAdded));
            me.increaseUnsentIndex(parseInt(answer.numSent));
            if (!me.needToSendMore() || answer.numAdded == 0) {
                if (me.callback != null) {
                    me.callback(me.numFriendsSent);
                }
                return;
            }
            me.doSend();
        }

        this.getHtml = function () {
            return this.html;
        }
    };var CODE_OK = 'ok';
var CODE_ERROR = 'error';
var CODE_REPEAT = 'repeat';

function callbackAddSubscribeNetworks(errors,auth,code,data) {
    if (errors) {
        return;
    }

    switch (code) {
        case CODE_OK:
            log_debug('ok: AddSubscribeNetworks');
            break;
        case CODE_ERROR:
            log_debug('error: AddSubscribeNetworks - '+data.error);
            break;
    }
}

function callbackAddSubscribeJournal(errors,auth,code,data) {
    if (errors) {
        return;
    }

    switch (code) {
        case CODE_OK:
            log_debug('ok: AddSubscribeJournal '+data.id);
            break;
        case CODE_REPEAT:
            log_debug('repeat: AddSubscribeJournal '+data.id);
            break;
        case CODE_ERROR:
            log_debug('error: AddSubscribeJournal '+data.id+' - '+data.error);
            break;
    }
}

function callbackAddSubscribeComments(errors,auth,code,data) {
    if (errors) {
        return;
    }

    switch (code) {
        case CODE_OK:
            log_debug('ok: AddSubscribeComments '+data.id);
            break;
        case CODE_REPEAT:
            log_debug('repeat: AddSubscribeComments '+data.id);
            break;
        case CODE_ERROR:
            log_debug('error: AddSubscribeComments '+data.id+' - '+data.error);
            break;
    }

}
function callbackAddFriend(errors,auth,code,data) {
    if (errors) {
        return;
    }

    switch (code) {
        case CODE_OK:
            var guyId = data.friend_id
            var labelAction = data.label_action;
            var label = document.getElementById('myFriend_' + guyId);
            if (label != null && labelAction != 'move') {
                label.style.display = "inline";
            }
            setAddRemoveLinkMode(false, guyId, labelAction);
            break;
        case CODE_REPEAT:
            debug('Этот чувак уже ваш друг! Че такое?');
            break;
        case CODE_ERROR:
            break;
    }
}

function setAddRemoveLinkMode(addMode, guyId, labelAction) {
    if (labelAction == 'change_label') {
        $('#addFriend_'+guyId).css('display', (addMode ? 'none' : 'inline'));
        $('#removeFriend_'+guyId+'.link').css('display', (addMode ? 'inline' : 'none'));
    } else if (labelAction == 'remove_label') {
        $('#addRemoveFriend_' + guyId).css('display', 'none');
    } else if (labelAction == 'move') {
        $('#myFriend_'+guyId).css('display', 'none');
    }
}

function callbackRemoveFriend(errors,auth,code,data) {
    if (errors) {
        return;
    }
    switch (code) {
        case CODE_OK:
            var guyId = data.friend_id;
            $('#myFriend_' + guyId).css('background-color', 'white');
            $('#myFriend_' + guyId+ '.regular').css('display', 'none');
            $('#removeFriend_' + guyId).css('display', 'none');
            setAddRemoveLinkMode(true, guyId, 'change_label');
            break;
        case CODE_REPEAT:
            debug('Это уже ваш друг! Smth goes wrong.');
            break;
        case CODE_ERROR:
            break;
    }
}

function callbackIncreaseCommentRating(errors,auth,code,data) {
    if (errors) {
        return;
    }
    switch (code) {
        case CODE_OK:
            commentId = data.comment_id;
            var label = document.getElementById('comment_rating_label_' + commentId);
            label.innerHTML = data.new_rating;
            label.style.fontWeight = 'bold';

            if (data.poor_lev!=null) {
                $('#comment_' + commentId).removeClass(function (index, classes) {
                    var matches = classes.match (/fog\d+/g) || [];
                    return (matches.join (' '));
                }).addClass('fog' + data.poor_lev);
            }

            if (!data.god_mode) {
                var label_down = document.getElementById('comment_rating_label_down_' + commentId);
                label_down.style.display = 'block';
                var link_down = document.getElementById('comment_rating_link_down_' + commentId);
                link_down.style.display = 'none';
                var label_up = document.getElementById('comment_rating_label_up_' + commentId);
                label_up.style.display = 'block';
                var link_up = document.getElementById('comment_rating_link_up_' + commentId);
                link_up.style.display = 'none';
            }
            break;
        case CODE_ERROR:
            break;
    }
}

function callbackIncreasePostRating(errors,auth,code,data) {
    if (errors) {
        return;
    }
    switch (code) {
        case CODE_OK:
            var postId = data.post_id;
            var label = document.getElementById('post_rating_label_' + postId);
            label.innerHTML = data.new_rating;
            label.style.fontWeight = 'bold';
            if (!data.god_mode) {
                var label_down = document.getElementById('post_rating_label_down_' + postId);
                label_down.style.visibility = 'visible';
                var link_down = document.getElementById('post_rating_link_down_' + postId);
                link_down.style.visibility = 'hidden';
                var label_up = document.getElementById('post_rating_label_up_' + postId);
                label_up.style.visibility = 'visible';
                var link_up = document.getElementById('post_rating_link_up_' + postId);
                link_up.style.visibility = 'hidden';
            }
            break;
        case CODE_ERROR:
            break;
    }
}

function callbackIncreaseUserRating(errors,auth,code,data) {
    if (errors) {
        return;
    }
    switch (code) {
        case CODE_OK:
            var userId = data.user_id;
            var label = document.getElementById('user_competence');
            label.innerHTML = data.new_rating;
            label.style.fontWeight = 'bold';
            break;
        case CODE_ERROR:
            break;
    }
}

function callbackMarkMessageRead(errors,auth,code,data) {
    if (errors) {
        return;
    }
    switch (code) {
        case CODE_OK:
            var numUnread = data.num_unread;
            var messageId = data.message_id;
            var block = document.getElementById('message_block_' + messageId);
            block.style.backgroundColor = 'white';
            break;
        case CODE_ERROR:
            break;
    }
}

function callbackRemoveMessage(errors,auth,code,data) {
    if (errors) {
        return;
    }
    switch (code) {
        case CODE_OK:
            var numUnread = data.num_unread;
            var messageId = data.message_id;
            var block = document.getElementById('message_block_' + messageId);
            block.parentNode.removeChild(block);
            break;
        case CODE_ERROR:
            break;
    }
}

function callbackRemoveComment(errors,auth,code,data) {
    if (errors) {
        return;
    }
    switch (code) {
        case CODE_OK:
            var commentId = data.comment_id;
            $('#comment_' + commentId).html("Комментарий удалён");
            break;
        case CODE_ERROR:
            break;
    }
}

function callbackRemoveClubPost(errors,auth,code,data) {
    if (errors) {
        return;
    }
    switch (code) {
        case CODE_OK:
            var postId = data.post_id;
            var block = document.getElementById('entry-' + postId);
            block.parentNode.removeChild(block);
            break;
        case CODE_ERROR:
            break;
    }
}

function callbackSetMaterialStatus(errors, auth, code, data) {
    if (errors) {
        return;
    }
    switch (code) {
        case CODE_OK:
            var entryId = data.entry_id;
            var status = data.status;
            var state = (status == 1) ? 'Проверено' : 'Отклонено';
            $('#state-label-row-'+entryId).css('display', 'table-row');
            $('#state-label-'+entryId).html(state);
            $('#approve-link-'+entryId).css('display', (status == 1) ? 'none' : 'table-row');
            $('#reject-link-'+entryId).css('display', (status == 1) ? 'table-row' : 'none');
            break;
        case CODE_ERROR:
            break;
    }
}

function usersAddSubscribeNetwork(id, callback) {
    var params = {
        'id': id,
        'type': 2
    };
    execApi('users', 'add_like', params, callback);
}

function usersAddSubscribeNetworks(networks) {
    var params = {
        'subscribe_type' : 'networks',
        'set_id': networks
    };
    execApi('users','add_subscribes',params,callbackAddSubscribeNetworks);
}

function usersAddFriend(user_id, label_action) {
    var params = {
        'friend_id': user_id,
        'label_action' : label_action
    };
    execApi('users', 'add_friend', params, callbackAddFriend);
}

function usersRemoveFriend(user_id) {
    var params = {
        'friend_id': user_id
    };
    execApi('users', 'remove_friend', params, callbackRemoveFriend);
}

function usersIncreaseCommentRating(commentId, incrementValue) {
    var params = {
        'comment_id': commentId,
        'increment' : incrementValue
    };
    execApi('users', 'increase_comment_rating', params, callbackIncreaseCommentRating);
}


function usersIncreasePostRating(staticId, incrementValue) {
    var params = {
        'static_id': staticId,
        'increment' : incrementValue
    };
    execApi('users', 'increase_post_rating', params, callbackIncreasePostRating);
}

function usersMarkMessageRead(messageId) {
    var params = {
        'message_id': messageId
    };
    execApi('users', 'mark_message_read', params, callbackMarkMessageRead);
}

function usersRemoveMessage(messageId, receiver) {
    var params = {
        'message_id': messageId,
        'receiver' : receiver
    };
    execApi('users', 'remove_message', params, callbackRemoveMessage);
}

function usersRemoveComment(messageId) {
    var params = {
        'comment_id': messageId
    };
    if (confirm("Вы хотите скрыть комментарий?")) {
        execApi('users', 'remove_comment', params, callbackRemoveComment);
    }
}

function usersRemoveClubPost(postId, entryType) {
    var params = {
        'post_id': postId,
        'entry_type' : entryType
    };

    if (confirm("Вы хотите скрыть запись?")) {
        execApi('users', 'remove_club_post', params, callbackRemoveClubPost);
    }
}

function usersSetMaterialStatus(entryId, entryType, status) {
    var params = {
        'entry_id': entryId,
        'entry_type': entryType,
        'status' : status
    };
    execApi('users', 'set_material_status', params, callbackSetMaterialStatus);
}

function usersLogin(callback) {
    if (callback) {
        addApiCallBack(function (errors,auth,code,data) {
            callback();
        });
    } else {
        setApiRedirectUrl(window.location + '');
    }
    authorization();
}

function findSocialFriends () {
    if (viewerId == 0) {
        usersLogin(function() {
            if (viewerId != 0) {
                setApiRedirectUrl(getFindFriendsUrl(viewerId));
            }
        });
    } else {
        window.location = getFindFriendsUrl(viewerId);
    }
}

function getFindFriendsUrl(userId) {
    return "/cabinet/" + userId + "/friends/find_social";
}

function showClubRegistrationDlg(networkId) {
    log_debug('club registration');
    api_data['status'] = 2;

    api_data['auth_closed_by_user'] = 0;

    addApiCallBack(function (errors,auth,code,data) {
        usersAddSubscribeNetwork(networkId);
    });
    $.fn.colorbox({
        href:'#dlgClubAuthorization',
        inline:true,
        open:true,
        overlayClose:false,
        onClosed:authCancel,
        onOpen: function(){
            $('#colorbox').css('z-index', '1000');
            $('#cboxOverlay').css('z-index', '1000');
        }
    });
}
;	
function callbackGetLikeThings(errors,auth,code,data) {
    if (errors) {
        return;
    }
    switch (code) {
        case 'ok':
            $('#' + data.block_id).html(data.block);
            break;
        case 'error':
        default:
            $('#' + data.block_id).html('');
    }
}
	
function ajaxGetLikeThings(block_id,thing_id,geo_id,index) {
    var params = {
        'block_id': block_id,
        'thing_id': thing_id,
        'geo_id': geo_id,
        'index': index
    };
		
    execApi('ajax', 'get_like_things', params, callbackGetLikeThings);
}

function callbackGetMainFashionBlock(errors,auth,code,data) {
    if (errors) {
        return;
    }
    switch (code) {
        case 'ok':
            $('#html_mainfashion').html(data.block);
            break;
        case 'error':
        default:
            $('#html_mainfashion').html('');
    }
}
	
function ajaxGetMainFashionBlock(static_id) {
    var params = {
        'static_id': static_id
    };
    execApi('ajax', 'get_main_fashion_block', params, callbackGetMainFashionBlock);
}
	
function callbackGetHeroBlock(errors,auth,code,data) {
    if (errors) {
        return;
    }
    switch (code) {
        case 'ok':
            $('#html_hero').html(data.block);
            break;
        case 'error':
        default:
            $('#html_hero').html('');
    }
}
    
function ajaxGetHeroBlock(index) {
    var params = {
        'hero_index': index
    };
    execApi('ajax', 'get_hero_block', params, callbackGetHeroBlock);
}
    	
    
function callbackGetBestEventBlock(errors,auth,code,data) {
    if (errors) {
        return;
    }
    switch (code) {
        case 'ok':
            $('#html_best_events').html(data.block);
            break;
        case 'error':
        default:
            $('#html_best_events').html();
    }
}
    
function ajaxGetBestEventBlock(index) {
    var params = {
        'event_index': index
    };
    execApi('ajax', 'get_best_event_block', params, callbackGetBestEventBlock);
}        ;/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "pngFix"
 * Version: 1, 21.02.2011
 * by Grabov Alexey, grabovalex@gmail.com
 *                      
 *
 * Copyright (c) 2011 Grabov Alexey
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * @example $(function(){$('.examples').pngFix();});
 * @desc Fixes PNG's in div with class examples
 * --------------------------------------------------------------------
 */

(function($) {

jQuery.fn.pngFix = function(settings) {

	// Settings
	settings = jQuery.extend({
		blankgif: 'blank.gif'
	}, settings);

	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

	if (jQuery.browser.msie && (ie55 || ie6)) {
	
		jQuery(this).each(function() {

			var bgIMG;
			if((bgIMG = jQuery(this).css('background-image')) && bgIMG.indexOf(".png")!=-1)
			{
				var iebg = bgIMG.split('url("')[1].split('")')[0];
				jQuery(this).css('background-image', 'none');
				jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
			}
			
			var srcIMG;
			if((srcIMG = jQuery(this).attr('src')) && srcIMG.indexOf(".png")!=-1)
			{
				
				jQuery(this).attr('width',jQuery(this).width());
				jQuery(this).attr('height',jQuery(this).height());
	
				var prevStyle = '';
				var strNewHTML = '';
				var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
				var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
				var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
				var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
				var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
				var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
				if (this.style.border) {
					prevStyle += 'border:'+this.style.border+';';
					this.style.border = '';
				}
				if (this.style.padding) {
					prevStyle += 'padding:'+this.style.padding+';';
					this.style.padding = '';
				}
				if (this.style.margin) {
					prevStyle += 'margin:'+this.style.margin+';';
					this.style.margin = '';
				}
				var imgStyle = (this.style.cssText);
	
				strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
				strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
				strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
				strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
				strNewHTML += imgStyle+'"></span>';
				if (prevStyle != ''){
					strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
				}
	
				jQuery(this).hide();
				jQuery(this).after(strNewHTML);

			}
		});
	
	}
	
	return jQuery;

};

})(jQuery);
;jQuery.fn.butex = function(options){

    var options = jQuery.extend({
        little: 0,
		l: 0
    },options);

    jQuery('.butexl, .butexc, .butexr, .pod').pngFix(); // .babl_top, .babl_bottom, .babl_center,

    return this.each(function() {
        var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
        var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

        var timeoutId;

        if (options.little == 1) {
            jQuery(this).wrap('<div class="butexs1" />');
            var txt = jQuery(this).text();
            jQuery(this).html('<p><img src="img/small2.png"/></p>'+txt);
            jQuery('.butexs1 img').pngFix();

            jQuery(this).mousedown(function() {
                var txt = jQuery(this).text();
                jQuery(this).html('<p><img src="img/small1.png"/></p>'+txt);
                jQuery('.butexs1 img').pngFix();
            }).mouseup(function() {
                jQuery(this).html('<p><img src="img/small3.png"/></p>'+$(this).attr('altitle'));
                jQuery('.butexs1 img').pngFix();
            });
        } else {
            var liked = jQuery(this).attr('state') == 1;

            if (!liked) {
                jQuery(this).bind('click', function() {
                    jQuery(this).unbind('click');
                    var bablid = jQuery(this).attr('bablid');
                    jQuery('#'+bablid).fadeOut(0);

                    var entryId = jQuery(this).attr('entry_id');
                    var entryType = jQuery(this).attr('entry_type');
                    var params = {
                        'id': entryId,
                        'type': entryType
                    };
                    execApi('users', 'add_like', params, callbackAddLike);
                    if (options.l == 0) jQuery(this).removeClass('butex1').addClass('butex2');
                    var postFunctionName = 'like_' + entryType + '_' + entryId;
                    var postFunction = window[postFunctionName];
                    if (postFunction != null) {
                        postFunction();
                    }
                });
            } else {
                if (options.l == 0) $('.butexl, .butexc, .butexr').pngFix();
            }
        }

        if (options.babl == 1) {
            var bablid = jQuery(this).attr('bablid');

            var bubl = jQuery('#'+bablid);
            bubl.appendTo('body');
            var self = jQuery(this);

            self.hover(
                function() {
                    var entryId = self.attr('entry_id');
                    var entryType = self.attr('entry_type');
                    var loaded = jQuery('#babl_center_'+ entryType + '_' + entryId).children().size();
                    if (loaded == 0) {
                        var numLikes = self.attr('num_likes');
                        var params = {
                            'entry_id': entryId,
                            'entry_type': entryType,
                            'num_liked' : numLikes
                        };
                        execApi('ajax', 'get_like_btn_people', params, callbackGetLikedPeople);
                    } else {
                        clearTimeout(timeoutId);
                        showBabl();
                    }
                },
                function() {
                    clearTimeout(timeoutId);
                    timeoutId = setTimeout(function(){
                        hideBabl();
                    }, 500);
                }
            );
            bubl.hover(
                function() {
                    clearTimeout(timeoutId);
                },
                function() {
                    clearTimeout(timeoutId)
                    timeoutId = setTimeout(function(){
                        hideBabl();
                    }, 500);
                }
            );
        }

        function updateLikeLabel(type, id, numLiked) {
            var numLikesId = '#like_btn_' + type + '_likes_number_' + id;

            var i = 1;
            while ($(numLikesId+'_'+i).length != 0) {
                $(numLikesId+'_'+i).html(numLiked)
                i++;
            }
        }

        function callbackGetLikedPeople(errors, auth, code, data) {
            if (errors || code != CODE_OK || data.num_liked == 0) {
                return;
            }
            jQuery('#babl_center_'+ data.entry_type + '_'+data.entry_id).html(data.block);

            bubl.find('img').each(function(){
                jQuery(this).width(50);
                jQuery(this).height(50);
                jQuery(this).parent().wrap('<div style="width:50px; height:50px; float:left;" />');
            });
            bubl.find('p').css({
                clear: 'both'
            });

            showBabl();

            clearTimeout(timeoutId);
        }

        function callbackAddLike(errors, auth, code, data) {
            if (errors || code != CODE_OK) {
                return;
            }
            updateLikeLabel(data.type, data.id, data.num_liked);
            $('#babl_center_'+ data.type + '_'+data.id).html('');

            var btnId = '#like_btn_' + data.type + '_like_' + data.id;
            var i = 1;
            while ($(btnId+'_'+i).length != 0) {
                updateBtn(btnId+'_'+i);
                i++;
            }
        }

        function updateBtn(btnId) {
		  if (options.l == 0) {
            jQuery(btnId).find('.butexc').text($(btnId).attr('altitle'));
            jQuery(btnId).removeClass('butex2').addClass('butex3');
            $('.butexl, .butexc, .butexr').pngFix();

            if (jQuery.browser.msie && (ie55 || ie6)) {
                jQuery(btnId).find('.butexl').remove();
                jQuery(btnId).find('.butexr').remove();
                var txt = jQuery(btnId).find('.butexc').text();
                jQuery(btnId).find('.butexc').remove();
                jQuery(btnId).text(txt);
                jQuery(btnId).wrapInner('<div class="butexc" />')
                jQuery(btnId).find('.butexc').before('<div class="butexl">&nbsp;</div>').after('<div class="butexr">&nbsp;</div>');
                jQuery(btnId).find('.butexl').pngFix();
                jQuery(btnId).find('.butexr').pngFix();
                jQuery(btnId).find('.butexc').pngFix();
            }
		  }
		  else {
			jQuery(btnId).addClass('pressed');
		  }
        }

        function showBabl() {
            if(bubl.css('visibility') != "visible") {
                if ( jQuery.browser.msie && parseInt($.browser.version)<9)
                {
                    bubl.hide().css({
                        visibility: "visible"
                    });
                }
                else{
                    bubl.css({
                        opacity: 0,
                        visibility: "visible"
                    });
                }
            }

            var top = self.offset().top;
            var height = bubl.height();
            var widthThis = self.width();
            var left = self.offset().left;

            bubl.css({
                top: top-height-15,
                left: left-90+(widthThis/2)
            });
            if ( jQuery.browser.msie && parseInt($.browser.version)<9)
            {
                bubl.show();
                bubl.find('.babl_center').css('behavior', "url('/views/less/PIE.htc')");
            }
            else
            {
                bubl.animate({
			opacity: 1
		}, 400);
            }
            bubl.find('.babl_arrow_down').pngFix();
        }

        function hideBabl() {
            if ( jQuery.browser.msie && parseInt($.browser.version)<9)
            {
                bubl.hide().css({
                    visibility: "hidden"
                });
            }
            else
            {
                bubl.animate({
                    opacity: 0
                }, 400, function () {
                    bubl.css({
                        visibility: "hidden"
                    })
                });
            }

        }
    });
};

function setCookie(name, value, expiredays, path, domain, secure)
{
    if (expiredays)
    {
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        var expires = exdate.toGMTString();
    }
    document.cookie = name + "=" + escape(value) +
    ((expiredays) ? "; 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 add2wardrobe(thingId){
    var params = {
        'id': thingId,
        'type': 1
    };
    execApi('users', 'add_like', params);
};$(document).ready(function(){
    var timeoutFloater = new Object();
    var timeoutFloaterStart = new Object();

    $('.floater_link img.photo').hover(
        function(){
            var self = $(this).closest('.floater_link');
            var entryId = self.attr('entryId');
            clearTimeout(timeoutFloater[entryId]);

            timeoutFloaterStart[entryId] = setTimeout(function(){
                var floater = '#floater_'+entryId;
                if($(floater).size()==0)
                {
                    var params = {
                        'entryId': entryId
                    };

                    execApi('ajax', 'get_info_bubble', params, callbackGetInfoBubble);
                }
                else{
                    floaterShow(self, floater);
                }
            }, 500);
        },function(){
            var self = $(this).closest('.floater_link');
            var entryId = self.attr('entryId');
            var floater = '#floater_'+entryId;

            clearTimeout(timeoutFloaterStart[entryId]);

            clearTimeout(timeoutFloater[entryId]);
            timeoutFloater[entryId] = setTimeout(function(){
                floaterHide(floater);
            }, 500);
        }
    );

    function floaterHide(floater){
        $(floater).css('display','none');
    }

    function floaterShow(self, floater){
        $(floater).css('display','block');

        var widthMiddle = $('#middle').width();
        var leftMiddle = $('#middle').offset().left;

        var width = self.width();
        var left = self.offset().left;

        var top = self.offset().top;
        var height = self.height();

        var heightFloater = $(floater).height();
        var widthFloater = $(floater).width();

        top = top-(heightFloater/2);
        if(top < $(document).scrollTop())
        {
            top+=$(document).scrollTop()-top;
            $(floater).find('.floater_arrow').css('display', 'none');
        }
        else
        {
            $(floater).find('.floater_arrow').css('display', 'block');
        }

        if((widthMiddle+leftMiddle+100) < width+left+widthFloater){
            $(floater).find('.floater_arrow').removeClass('float_arrow_right').addClass('float_arrow_left');

            $(floater).css({
                top: top,
                left: left-widthFloater
            });
        }
        else{
            $(floater).find('.floater_arrow').removeClass('float_arrow_left').addClass('float_arrow_right');

            $(floater).css({
                top: top,
                left: (width+left)
            });
        }
        if (!(jQuery.browser.msie && jQuery.browser.version == '9.0'))
            $(floater).find('.floater_border').css('behavior', 'url(/views/less/PIE.htc)');
    }

    function callbackGetInfoBubble(errors, auth, code, data) {

        if (errors) {
            return;
        }
        switch (code) {
            case 'ok':
                $(data.block).appendTo('body');
                floaterShow($('.floater_link[entryId="'+data.entryId+'"]'), '#floater_'+data.entryId);
                
                $('#floater_'+data.entryId).hover(
                    function(){
                        clearTimeout(timeoutFloater[data.entryId]);
                    },
                    function(){
                        clearTimeout(timeoutFloater[data.entryId])
                        timeoutFloater[data.entryId] = setTimeout(function(){
                            floaterHide('#floater_'+data.entryId);
                        }, 500);
                    }
                );
                break;
            case 'error':
            default:
                break;
        }
    }

});
;$(document).ready(function(){
    
        var methods_SelectButtons = {
            clear : function() {
                return this.each(function() {
                    jQuery(this).trigger('clear');
                });
            },
            //$('.select_button[name="kind"]').select_button('big_addOption', 'Блаблабла');
            big_addOption: function(title, clear){
                if(clear == null) clear=true;
                return this.each(function() {
                    var self = jQuery(this);
                    var opts = self.find('.select_button_options_big');
                    var element = jQuery('<div />', {
                        "class": 'select_button_option_big'
                    }).html('<h5>'+title+'</h5>');
                    opts.append(element);
                    if(opts.find('.select_button_option_big').size()%3==0 && clear)
                        opts.append('<div class="clear"></div>');
                });
            },
            //$('.select_button[name="kind"]').select_button('big_addElement', 'last', {entryId: 111, text: 'бла бла'});
            big_addElement: function(to, el){
                return this.each(function() {
                    var self = jQuery(this);
                    var opts = self.find('.select_button_options_big');
                    var bigs = opts.find('.select_button_option_big');
                    
                    if (to=='last') to = bigs.size()-1;
                    else if (to=='first') to = 0;

                    var element = jQuery('<a/>', {
                        href: 'javascript:void(0);',
                        entryId: el.entryId,
                        text: ' '+el.text
                    }).addClass('select_button_option_item');
                    
                    if( bigs.find('.select_button_option_item').size()<1 ) {
                        self.find('.select_button_text').text(self.attr('pref')+el.text);
                        self.attr('entryId', el.entryId);
                    }

/*
                    var elems = bigs.eq(to).find('.select_button_option_item').size();
                    if (elems == 5){
                        bigs.eq(to).append('<a href="javascript:void(0);" class="select_button_option_more">еще &gt;</a>');
                    }
                    
                    if (elems >= 5){
                        bigs.eq(to).append(element.addClass('closer')).append('&nbsp;');
                    }
                    else{
                        bigs.eq(to).append(element).append('&nbsp;&nbsp;');
                    }
*/
                    bigs.eq(to).append(element);
                });
            },
            big_fill: function(data, group, oneline){
                return this.each(function() {
                    var self = $(this);
                    for(ite in data) {
                        if(data[ite][0]['PTName']==null) data[ite][0]['PTName']='';
                        self.select_button('big_addOption', data[ite][0]['PTName'], false);
                        for(opt in data[ite]) {
                            self.select_button('big_addElement', 'last', {
                                entryId: data[ite][opt]['PId'],
                                text: data[ite][opt]['PName']
                            });
                        }
                    }
                    var opts = self.find('.select_button_option_big');
                    if(group!=null && group!=false){
                        var sep = $('<div style="float:left;width: 185px;" />');

                        opts.eq(0).add(opts.eq(1)).add(opts.eq(2)).wrapAll(sep);
                        opts.eq(3).add(opts.eq(4)).add(opts.eq(5)).wrapAll(sep);
                        opts.eq(6).add(opts.eq(7)).add(opts.eq(8)).wrapAll(sep);
                    }
                    if(oneline!=null && group!=false){
                        opts.find('.select_button_option_item').css('display', 'block');
                    }
                });
            },
            big_group: function(){
                return this.each(function() {
                    var self = $(this);
                    var opts = self.find('.select_button_option_big');
                    var sep = $('<div style="float:left;width: 185px;" />');

                    opts.eq(0).add(opts.eq(1)).add(opts.eq(2)).wrapAll(sep);
                    opts.eq(3).add(opts.eq(4)).add(opts.eq(5)).wrapAll(sep);
                    opts.eq(6).add(opts.eq(7)).add(opts.eq(8)).wrapAll(sep);
                    
                    self.find('.select_button_options_big .clear').remove();
                });
            },
            //$('.select_button[name="kind"]').select_button('big_clear');
            big_clear: function(){
                return this.each(function() {
                    var self = $(this);
                    var opts = self.find('.select_button_options_big');
                    opts.empty();
                });
            },
            //$('.select_button[name="kind"]').select_button('big_select', 15);
            big_select: function(entryId){
                return this.each(function() {
                    var self = jQuery(this);
                    var opt = self.find('.select_button_option_big');
                    opt.find('a.select_button_option_item[entryId="'+entryId+'"]').click();
                });
            },
            big_removeElement : function(entryId){
                return this.each(function() {
                    var self = jQuery(this);
                    self.find('a.select_button_option_item[entryId="'+entryId+'"]').remove();
                });                
            },
            addElement : function(el) {
                return this.each(function() {
                    var self = jQuery(this);
                    var opt = self.find('.select_button_option');
                    var element = jQuery('<a/>', {
                        href: 'javascript:void(0);',
                        entryId: el.entryId,
                        text: el.text
                    }).addClass('select_button_option_item');
                    
                    if( opt.find('.select_button_option_item').size()<1 ) {
                        self.find('.select_button_text').text(self.attr('pref')+el.text);
                        self.attr('entryId', el.entryId);
                    }
                    
                    opt.append(element);
                });
            },
            close : function () {
                return this.each(function() {
                    jQuery(this).trigger('close');
                });
            },
            removeElement : function(entryId){
                return this.each(function() {
                    var self = jQuery(this);
                    var opt = self.find('.select_button_option');
                    opt.find('a.select_button_option_item[entryId="'+entryId+'"]').remove();
                });                
            },
            select : function(entryId){
                return this.each(function() {
                    var self = jQuery(this);
                    var opt = self.find('.select_button_option');
                    opt.find('a.select_button_option_item[entryId="'+entryId+'"]').click();
                });                
            },
            disabled : function () {
                return this.each(function() {
                    jQuery(this).trigger('close');
                    jQuery(this).addClass('disabled');
                });
            },
            enabled : function () {
                return this.each(function() {
                    jQuery(this).removeClass('disabled');
                });
            }
        };
        
    jQuery.fn.select_button = function(options){

        if ( methods_SelectButtons[options] ) {
            return methods_SelectButtons[ options ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else
    
            return this.each(function() {

                var self = jQuery(this);
                self.css('z-index', $('.select_button').size()-self.index('.select_button')+1); // z-index от большого к маленкьому, чтоб пред перекрывал след
                var text = self.find('.select_button_text');
                var options = self.find('.select_button_options');
                var input = self.find('input[name="'+self.attr('name')+'"]');
                var prefix = self.attr('pref');
                if(prefix==undefined) prefix='';

                var postfix = self.attr('postf');
                if(postfix==undefined) postfix='';
                        
                var lower = self.attr('lower');
                if(lower==undefined) lower=0;
                        
                self.unbind('click').bind('click', function(e){
                    if(options.is(":visible")){
                        options.hide();
                        options.css({
                            'behavior': 'none'
                        });
                    }
                    else{
                        $('.select_button').select_button('close');
                        if(!self.hasClass('disabled')) {
                            options.css('top', self.height());
                            options.show();
                            if (!(jQuery.browser.msie && jQuery.browser.version == '9.0'))
                                options.css({
                                    'behavior': 'url(/views/less/PIE.htc)'
                                });
                        }
                    }
                    e.stopPropagation();
                });

                self.unbind('close').bind('close', function(){
                    if(options.is(":visible")){
                        options.hide();
                        if (!(jQuery.browser.msie && jQuery.browser.version == '9.0'))
                            options.css({
                                'behavior': 'none'
                            });
                    }                            
                });

                self.unbind('clear').bind('clear', function(){
                    options.find('.select_button_option_item').remove();
                    self.find('.select_button_text').text(self.attr('pref'));
                    self.attr('entryId', '');
                });

                options.find('.select_button_option_more').unbind('click').bind('click', function(event){
                    event.stopPropagation();
                    var more = jQuery(this);
                    more.closest('.select_button_option_big').find('a:hidden').show();
                    more.remove();
                });

			options.find('.select_button_option_item').die('click').live('click',function(){
				var a = jQuery(this);
                                
                                atext = a.text();
                                if (lower==1) atext = atext.toLowerCase();
                                atext = prefix+atext;
                                if (a.attr('entryId')!=0) atext = atext+postfix
				text.text(atext);
                                
				self.attr('entryId', a.attr('entryId'));
				input.val(a.attr('entryId'));
                                self.trigger('selected');
                                self.click();
                                self.trigger('close');
                                return false;
			});

		});
	};
	$('.select_button').select_button();
    
    /* прячем по эксейпу */
    $(document).keyup(function(e){
         if (e.which == 27 || e.keyCode == 27){
            $('.select_button').trigger('close');
        }
    });
    /* закрываем по клику вне */
    $('html').click(function() {
        $('.select_button').trigger('close');
    });
});

function getSelectButtonParams(name){
    var arr = new Array();
    $('form[name="'+name+'"] .select_button').each(function(){
            var self = $(this);
            arr.push(self.attr('name') + "=" + self.attr('entryId'));
    });
    var string = ( ( arr instanceof Array ) ? arr.join ( '&' ) : arr );
    return string;
};$(document).ready(function(){
    function buttons(self, add, remove) {
        if(self.attr('state')!='1'){
            var params = {
                'id': self.attr('entry_id'),
                'type': 2
            };
            execApi('users', 'add_like', params,
                function (errors, auth, code, data) {
                    if (errors) {
                        return;
                    }
                    add();
                    self.attr('state', '1');
                }
            );
        }else{
            var params = {
                'id': self.attr('entry_id'),
                'type': 2
            };
            execApi('users', 'remove_like', params,
                function (errors, auth, code, data) {
                    if (errors) {
                        return;
                    }
                    remove();
                    self.attr('state', '0');
                }
            );
        }
    }

    $('.follow_shop').click(function(){
        var self = $(this);
        buttons(
            self,
            function(){
                self.text('+ вы следите');
            },
            function(){
                self.text('+ следить');
            }
        );
    });

    $('.plus_shop').click(function(){
        var self = $(this);
        buttons(
            self,
            function(){
                self.addClass('plus_shop_v');
            },
            function(){
                self.removeClass('plus_shop_v');
            }
        );
    });
    
    $(".towarb").live("click", function(){
        var self = $(this);
        var alt = self.attr('alttext');
        buttons(
            self,
            function(){
                self.attr('alttext', self.find('.towarb_c').text());
                self.find('.towarb_c').text(alt);
                self.addClass('towarb2');
            },
            function(){
                self.attr('alttext', self.find('.towarb_c').text());
                self.find('.towarb_c').text(alt);
                self.removeClass('towarb2');
            }
        );
    });
});
;jQuery.fn.bubling = function(){

    return this.each(function() {

        var self = jQuery(this);
        var entryId = self.attr('entry_id');
        var entryType = self.attr('entry_type');
        var btn_i = self.attr('btn_i');
        var bablid = 'babl_'+entryType+'_'+entryId+'_'+btn_i;

        var bubl = jQuery('#'+bablid);
        bubl.appendTo('body');
        var bubl_center = bubl.find('.babl_center');

        var timeoutId;

        self.hover(
            function(){
                var loaded = bubl_center.children().size();
                if (loaded == 0) {
                    var numLikes = self.attr('num_likes');
                    var params = {
                        'entry_id': entryId,
                        'entry_type': entryType,
                        'num_liked' : numLikes
                    };
                    execApi('ajax', 'get_like_btn_people', params, function(errors, auth, code, data){
                        if (errors || code != CODE_OK || data.num_liked == 0) {
                            return;
                        }
                        bubl_center.html(data.block);

                        bubl.find('img').each(function(){
                            jQuery(this).width(50);
                            jQuery(this).height(50);
                            jQuery(this).parent().wrap('<div style="width:50px; height:50px; float:left;" />');
                        });
                        bubl.find('p').css({
                            clear: 'both'
                        });

                        showBabl();

                        clearTimeout(timeoutId);
                    });
                } else {
                    clearTimeout(timeoutId);
                    showBabl();
                }

            },
            function(){
                clearTimeout(timeoutId);
                timeoutId = setTimeout(function(){
                    hideBabl();
                }, 500);
            }
        );

        bubl.hover(
            function() {
                clearTimeout(timeoutId);
            },
            function() {
                clearTimeout(timeoutId)
                timeoutId = setTimeout(function(){
                    hideBabl();
                }, 500);
            }
        );

        function showBabl() {
            if(bubl.css('visibility') != "visible") {
                if ( jQuery.browser.msie && parseInt($.browser.version)<9)
                {
                    bubl.hide().css({
                        visibility: "visible"
                    });
                }
                else{
                    bubl.css({
                        opacity: 0,
                        visibility: "visible"
                    });
                }
            }

            var top = self.offset().top;
            var height = bubl.height();
            var widthThis = self.width();
            var left = self.offset().left;

            bubl.css({
                top: top-height-15,
                left: left-90+(widthThis/2)
            });
            if ( jQuery.browser.msie && parseInt($.browser.version)<9)
            {
                bubl.show();
                bubl.find('.babl_center').css('behavior', "url('/views/less/PIE.htc')");
            }
            else
            {
                bubl.animate({
                        opacity: 1
                }, 400);
            }
            bubl.find('.babl_arrow_down').pngFix();
        }

        function hideBabl() {
            if ( jQuery.browser.msie && parseInt($.browser.version)<9)
            {
                bubl.hide().css({
                    visibility: "hidden"
                });
            }
            else
            {
                bubl.animate({
                    opacity: 0
                }, 400, function () {
                    bubl.css({
                        visibility: "hidden"
                    })
                });
            }

        }
    });
}
;var bnr = {
    selector: "#cl_im_r_bn_1",
    intervalId: null,
    intervaling: null,
    countRefresh: 0,

    refresh: function (isclick){

        if(isclick === undefined){
            isclick = true;
        }
        
        if(isclick == false){
            if(this.countRefresh!=0) this.countRefresh--;
            else{
                clearInterval(this.intervalId);
                return;
            }
        }

        $(this.selector).html('<iframe scrolling="no" src="/postload/ajaxb/?refriframe=1&q='+encodeURIComponent(window.location.search)+'" style="width: 300px; height: 500px;overflow: hidden; border: 0px none;"></iframe>');
        if(this.intervaling==true && isclick==true){
            this.interval();
        }
    },
    
    interval: function(){
        this.intervaling = true;
        clearInterval(this.intervalId);
        this.intervalId = setInterval(function(){bnr.refresh(false)}, 20000);
    }
};;
(function($){$.toJSON=function(o)
{if(typeof(JSON)=='object'&&JSON.stringify)
return JSON.stringify(o);var type=typeof(o);if(o===null)
return"null";if(type=="undefined")
return undefined;if(type=="number"||type=="boolean")
return o+"";if(type=="string")
return $.quoteString(o);if(type=='object')
{if(typeof o.toJSON=="function")
return $.toJSON(o.toJSON());if(o.constructor===Date)
{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array)
{var ret=[];for(var i=0;i<o.length;i++)
ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;if(typeof o[k]=="function")
continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
{if(string.match(_escapeable))
{return'"'+string.replace(_escapeable,function(a)
{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);;var FB_ID = 1;
var VK_ID = 2;
var MR_ID = 3;

var BEIN_GENDER_UNDEFINED = 0;
var BEIN_GENDER_MALE = 1;
var BEIN_GENDER_FEMALE = 2;

function getSocialConnector() {
	if (window.connector) {
		return window.connector;
	}
	window.connector = new SocialConnector();
	window.connector.connect();
	return window.connector;
}

function SocialConnector() {
	this.connectors = {};
	this.listeners = {};
	this.buttons = {};
	this.clickAction = null;
	this.onError = null;

	var me = this;

	this.connect = function () {
		this.connectors[FB_ID] = new FBConnect(FB_ID);
		this.connectors[VK_ID] = new VKConnect(VK_ID);
		this.connectors[MR_ID] = new MRConnect(MR_ID);

		for (var id in this.connectors) {
			this.connectors[id].init();
		}
	}

	this.logout = function (id) {
		this.connectors[id].logout();
	}

	this.login = function (id, onLogin, onError) {
	    this.onError = onError;
		this.connectors[id].login(onLogin, me.onError);
	}

	this.onLogout = function (netId) {
//		alert('Logged out from: ' + netId);
	}

	this.addListener = function (eventType, listener) {
		var theListeners = this.listeners[eventType];
		if (theListeners == null) {
			theListeners = [];
			this.listeners[eventType] = theListeners;
		}
		theListeners.push(listener);
	}

	this.registerButton = function (netId, button, callback, onClickAction) {
		var theButtons = this.buttons[netId];
		if (theButtons == null) {
			theButtons = [];
			this.buttons[netId] = theButtons;
		}
		theButtons.push(button);
		button.clickAction = onClickAction;
		button.onclick = function () {
		    if (button.clickAction != null) {
		        button.clickAction();
		    }
			me.login(netId, callback, function (data) {
			    callback({error : data});
			});
		}
	}

	this.postToWalls = function (message, link, picture, title) {
        for (var id in this.connectors) {
            var posted = this.connectors[id].postToWall(message, link, picture, title);
            if (posted) {
                break;
            }
        }
	}
	return true;
}

function FBConnect(id) {
	var FB_GENDER_MALE = "male";
	var FB_GENDER_FEMALE = "female";

	this.id = id;
	this.onLogin = null;
    this.onError = null;
	this.loggedIn = false;
	this.inited = false;

    this.errorPrefix = 'Произошла ошибка при подключении к Facebook';

	var me = this;

	this.getId = function () {
		return id;
	}

	this.connect = function() {
        FB.Event.subscribe('auth.login', function(response) {
            if (response.session) {
            	me.loggedIn = true;
            } else {
            }
        });
        FB.Event.subscribe('auth.logout', function(response) {
//        	onLogout(FB_ID);
        });

        FB.init({appId: FB_APP_ID, status: true, cookie: true, xfbml: true, oauth: true});
    }

	this.init = function() {
		if (this.inited) {
			return;
		}
	    window.fbAsyncInit = this.connect;

		var e = document.createElement('script');
	    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
	    e.async = true;
	    document.getElementById('fb-root').appendChild(e);
	    this.inited = true;
	}

	this.login = function(_onLogin, _onError) {
		this.onLogin = _onLogin;
		this.onError = _onError;
		if (this.loggedIn) {
    		this.getUserData(this.onLogin, this.onError);
			return;
		}
		FB.login(function(response) {
			if (response.authResponse) {
                me.getUserData(me.onLogin, me.onError);
			} else {
			    me.onError({message : me.errorPrefix + '<br/>'});
			}
		}, {scope:'read_stream,publish_stream,email,user_birthday'});
	}

	this.userDataParser = function (data) {
		var user = new Object();
		user.netId = FB_ID;
		user.id = data.id;
		user.first_name = data.first_name;
		user.last_name = data.last_name;
		user.gender = this.parseGender(data.gender);
		user.bdate = this.parseDate(data.birthday);
		user.email = data.email;
		user.link = data.link;
		user.location = data.location;
		user.pic = data.picture;
		return user;
	}

	this.parseDate = function (date) {
		//MM/DD/YYYY
		if (!date) {
			return '';
		}
		var d = new Date(date);
		var result = d.getFullYear() + '-' + (d.getMonth()+1) + '-' + d.getDate();
		return result;
	}

	this.parseGender = function (fbGender) {
		if (fbGender == FB_GENDER_MALE) {
			return BEIN_GENDER_MALE;
		} else if (fbGender == FB_GENDER_FEMALE) {
			return BEIN_GENDER_FEMALE;
		} else {
			return BEIN_GENDER_UNDEFINED;
		}
	}

	this.friendDataParser = function (friendData) {
		var friend = new Object();
		friend.id = friendData.id;
		return friend;
	}

	this.logout = function () {
		if (this.loggedIn) {
			FB.logout(null);
			this.userInfo = null;
			this.loggedIn = false;
		}
	}

	this.getUserData = function (_onSuccess, _onError) {
		if (this.userInfo) {
        	if (_onSuccess) {
        		_onSuccess(this.userInfo);
        	}
        	return;
		}
		FB.api('/me?fields=first_name,last_name,email,link,birthday,gender,location,picture&type=large&locale=en_US', function(userResponse) {
		    if (userResponse && !userResponse.error) {
		        FB.api('/me/friends?fields=id', function(friendsResponse) {
		            if (friendsResponse && !friendsResponse.error) {
		                me.userInfo = parseData(userResponse, friendsResponse.data, me);
		                if (_onSuccess) {
		                    _onSuccess(me.userInfo);
		                }
		            } else {
		                _onError({message : me.errorPrefix + ':<br/>' + userResponse.error.message});
		            }
		        });
		    } else {
		        _onError({message : me.errorPrefix + ':<br/>' + userResponse.error.message});
		    }
		});
	}

	this.postToWall = function (message, link, picture, title) {
	    if (!this.loggedIn) {
	        return false;
	    }
	    FB.api('/me/feed', 'post', {
	        message: title,
	        link : link,
	        picture : picture,
	        description : message
	    }, function(response) {});

	    return true;
	}
	return true;
}

function VKConnect(id) {
	var VK_GENDER_MALE = "2";
	var VK_GENDER_FEMALE = "1";

	this.id = id;
	this.onLogin = null;
	this.onError = null;
	this.loggedIn = false;
	this.inited = false;
	this.errorPrefix = 'Возникла ошибка при подключении к ВКонтакте';

	var me = this;

	this.getId = function () {
		return id;
	}

    this.connect = function() {
    	VK.Observer.subscribe('auth.login', function(response) {
        	if (response.session && response.session.mid &&
        	         response.status == 'connected') {
        		me.loggedIn = true;
        	}
        });
    	VK.Observer.subscribe('auth.logout', function(response) {
//            onLogout(VK_ID);
    	});
        VK.init({apiId: VK_APP_ID, nameTransportPath: "/views/social/xd_receiver.html", status: 1});
    };

	this.init = function () {
		if (this.inited) {
			return;
		}
		window.vkAsyncInit = this.connect;

        setTimeout(function() {
            var el = document.createElement("script");
            el.type = "text/javascript";
            el.charset = "utf-8";
            el.src = "http://vkontakte.ru/js/api/openapi.js";
            el.async = true;
            document.getElementById("vk_api_transport").appendChild(el);
            me.inited = true;
        }, 0);
	}

	this.login = function (_onLogin, _onError) {
		this.onLogin = _onLogin;
		this.onError = _onError;
		if (this.loggedIn) {
    		this.getUserData(this.onLogin, this.onError);
			return;
		}
		VK.Auth.login(function (response) {
		    if (response.session) {
		        me.getUserData(me.onLogin, me.onError);
		    } else {
                me.onError({message : me.errorPrefix});
		    }
		}, VK.access.FRIENDS | 1 | 512| 1024 | 2048);
	}

	this.logout = function () {
		if (this.loggedIn) {
			VK.Auth.logout();
			this.userInfo = null;
			this.loggedIn = false;
		}
	}

	this.getUserData = function (_onSuccess, _onError) {
		if (this.userInfo) {
        	if (_onSuccess) {
        		_onSuccess(this.userInfo);
        	}
        	return;
		}

		var code;
		code = 'return {me: API.getProfiles({uids: API.getVariable({key: 1280}), fields: "uid,first_name,last_name,nickname,bdate,sex,city,country,photo_big,"})[0],friends: API.friends.get({uids: API.getFriends()})};';
		VK.Api.call('execute', {'code': code}, function(data) {
		    if (data && data.response) {
		        me.userInfo = parseData(data.response.me, data.response.friends, me);
		        if (_onSuccess) {
		            _onSuccess(me.userInfo);
		        };
		    } else {
		        _onError({message: me.errorPrefix + ':<br/>' + data.error.error_msg});
		    }
		});
	}

	this.userDataParser = function (data) {
		var user = new Object();
		user.netId = VK_ID;
		user.id = data.uid;
		user.first_name = data.first_name;
		user.last_name = data.last_name;
		user.bdate = this.parseDate(data.bdate);
		user.gender = this.parseGender(data.sex);
		user.link = 'http://vkontakte.ru/id' + user.id;
		user.location = data.country + ':' + data.city;
		user.pic = data.photo_big;
		return user;
	}

	this.parseDate = function (date) {
		//DD.MM.YYYY
		if (!date) {
			return '';
		}
		var dateArr = date.split(".");
		var d = new Date(date);
		var result = dateArr[2] + '-' + dateArr[1] + '-' + dateArr[0];
		return result;
	}


	this.parseGender = function (vkGender) {
		if (vkGender == VK_GENDER_MALE) {
			return BEIN_GENDER_MALE;
		} else if (vkGender == VK_GENDER_FEMALE) {
			return BEIN_GENDER_FEMALE;
		} else {
			return BEIN_GENDER_UNDEFINED;
		}
	}

	this.friendDataParser = function (friendData) {
		var friend = new Object();
		friend.id = friendData;
		return friend;
	}

    this.postToWall = function (message, link, picture, title) {
        VK.Api.call('notes.add', {title: title, text : message + '\n' + link}, function(r) {
            if(r.response) {
//                alert('Привет, ' + r.response);
            }
        });

        return true;
    }
	return true;
}

function MRConnect(id) {
	var MR_GENDER_MALE = "0";
	var MR_GENDER_FEMALE = "1";

	this.id = id;
	this.onLogin = null;
	this.loggedIn = false;
	this.inited = false;

	this.errorPrefix = 'Не удалось войти в Mail.ru';

	var me = this;

	this.getId = function () {
		return id;
	}

	this.init = function () {
		if (this.inited) {
			return;
		}
	    mailru.loader.require('api', function() {
		    mailru.events.listen(mailru.connect.events.login, function(session){
	            if (session) {
	            	me.loggedIn = true;
	            }
		    });
            mailru.events.listen(mailru.connect.events.loginFail, function(session){
                me.loggedIn = false;
            });
		    mailru.events.listen(mailru.connect.events.logout, function(){
//	            onLogout(MR_ID);
		    });
            mailru.connect.init(MR_APP_ID, MR_APP_KEY);
		});
	    this.inited = true;
	}

	this.login = function(_onLogin, _onError) {
		this.onLogin = _onLogin;
		this.onError = _onError;
		if (this.loggedIn) {
    		this.getUserData(this.onLogin, this.onError);
			return;
		}
        mailru.events.listen(mailru.connect.events.login, function(session){
            if (session) {
                me.getUserData(me.onLogin, me.onError);
            } else {
                var msg = session ? session.error.error_msg : me.errorPrefix;
                me.onError({message : msg});
            }
        });
		mailru.connect.login();
	}

	this.getUserData = function (_onSuccess, _onError) {
		if (this.userInfo) {
        	if (_onSuccess) {
        		_onSuccess(this.userInfo);
        	}
        	return;
		}
	    mailru.common.users.getInfo(function(userResponse){
	        if (!userResponse.error) {
	            mailru.common.friends.getExtended(function(friendsResponse){
	                if (!friendsResponse.error) {
	                    me.userInfo = parseData(userResponse[0], friendsResponse, me);
	                    if (_onSuccess) {
	                        _onSuccess(me.userInfo);
	                    };
	                } else {
	                    _onError({message : me.errorPrefix + ': ' + friendsResponse.error.error_msg});
	                }
	            });
	        } else {
	            _onError({message : me.errorPrefix + ': ' + userResponse.error.error_msg});
	        }
	    });
	}

	this.userDataParser = function(data) {
		var user = new Object();
		user.netId = MR_ID;
		user.id = data.uid;
		user.first_name = data.first_name;
		user.last_name = data.last_name;
		user.gender = this.parseGender(data.sex);
		user.bdate = this.parseDate(data.birthday);
		user.email = data.email;
		user.link = data.link;
		user.location = data.location;
		user.pic = data.pic_big;
		return user;
	}

	this.parseGender = function (mrGender) {
		if (mrGender == MR_GENDER_MALE) {
			return BEIN_GENDER_MALE;
		} else if (mrGender == MR_GENDER_FEMALE) {
			return BEIN_GENDER_FEMALE;
		} else {
			return BEIN_GENDER_UNDEFINED;
		}
	}

	this.parseDate = function (date) {
		//DD.MM.YYYY
		if (!date) {
			return '';
		}
		var dateArr = date.split(".");
		var d = new Date(date);
		var result = dateArr[2] + '-' + dateArr[1] + '-' + dateArr[0];
		return result;
	}

	this.friendDataParser = function(friendData) {
		var friend = new Object();
		friend.id = friendData.uid;
		return friend;
	}

	this.logout = function() {
		if (this.loggedIn) {
			mailru.connect.logout();
			this.userInfo = null;
			this.loggedIn = false;
		}
	}

    this.postToWall = function (message, link, picture, title) {
        if (!this.loggedIn) {
            return false;
        }
        mailru.common.stream.post({
            'title' : title,
            'text' : message,
            'img_url' : picture,
            'action_links' : [{'text' : "подробнее", 'href' : link}]
        });
        return true;
    }
	return true;
}

function parseData(userData, friendsData, socialConnect) {
    var userInfo = new Object();
    if (userData) {
        userInfo.user = socialConnect.userDataParser(userData);
    }
    if (friendsData) {
        userInfo.friends = [];
        for (var i = 0; i < friendsData.length; i++) {
            var friend = socialConnect.friendDataParser(friendsData[i]);
            userInfo.friends.push(friend);
        }
    }
    if (!userData && !friendsData) {
        userInfo = null;
    }
    return userInfo;
}

function registerButtons($id, handler, onClickAction) {
	var connector = getSocialConnector();
	connector.registerButton(FB_ID, document.getElementById('fb_login_btn_' + $id), handler, onClickAction);
	connector.registerButton(VK_ID, document.getElementById('vk_login_btn_' + $id), handler, onClickAction);
	connector.registerButton(MR_ID, document.getElementById('mr_login_btn_' + $id), handler, onClickAction);
}

function postToWalls(message, link, picture, title) {
    var connector = getSocialConnector();
    connector.postToWalls(message, link, picture, title);
};jQuery.cookie = function(a, f, c) {
    if (typeof f != "undefined") {
        c = c || {};
        if (f === null) {
            f = "";
            c.expires = -1
        }
        var d = "";
        if (c.expires && (typeof c.expires == "number" || c.expires.toUTCString)) {
            if (typeof c.expires == "number") {
                d = new Date;
                d.setTime(d.getTime() + c.expires * 24 * 60 * 60 * 1E3)
            } else
                d = c.expires;
            d = "; expires=" + d.toUTCString()
        }
        var g = c.path ? "; path=" + c.path : "", h = c.domain ? "; domain=" + c.domain : "";
        c = c.secure ? "; secure" : "";
        document.cookie = [a, "=", encodeURIComponent(f), d, g, h, c].join("")
    } else {
        f = null;
        if (document.cookie && document.cookie != "") {
            c = document.cookie.split(";");
            for (d = 0; d < c.length; d++) {
                g = jQuery.trim(c[d]);
                if (g.substring(0, a.length + 1) == a + "=") {
                    f = decodeURIComponent(g.substring(a.length + 1));
                    break
                }
            }
        }
        return f
    }
};

(function(a) {
    a(document).ready(function() {
        function f() {
        }
        function c() {
        }
        function d(b) {
        }
        function g() {
            switch (window.orientation) {
                case 0:
                    l = 320;
                    j = 50;
                    i = 100;
                    break;
                case -90:
                    l = 480;
                    j = 100;
                    i = 200;
                    break;
                case 90:
                    l = 480;
                    j = 100;
                    i = 200;
                    break;
                case 180:
                    l = 320;
                    j = 50;
                    i = 100;
                    break
            }
        }
        function h(b) {
            if (b.type == "touchstart") {
                n = false;
                b.preventDefault();
                touching = true;
                if (b.touches.length == 1) {
                    b = b.touches[0];
                    oX = b.pageX
                }
            } else if (b.type == "touchmove") {
                n = true;
                b.preventDefault();
                if (b.touches.length == 1) {
                    b = b.touches[0];
                    b = b.pageX;
                    if (oX > b) {
                        b = oX - b;
                        if (b > j)
                            if (touching == true) {
                                touching = false
                            }
                    } else {
                        b = b - oX;
                        if (b > j)
                            if (touching == true) {
                                touching = false
                            }
                    }
                }
            } else if (b.type == "touchend") {
                touching = false;
                if (a(b.target).parent().is("a") && !n) {
                    b = a(b.target).parent("a").attr("href");
                    q(b)
                }
            } else if (b.type == "touchcancel")
                touching = false
        }
        function q(b) {
            window.location.assign(b)
        }
        function o() {
            var b = window.innerHeight + window.pageYOffset + "px", r = window.innerHeight + window.pageYOffset - 303 + "px"; //74
            a("#promo").css("top", b).show();
            a("#promo").animate({top: r})
        }
        function s() {
            a("#promo").hide()
        }
        function p() {
            var b = window.innerHeight + window.pageYOffset + "px";
            a("#promo").animate({top: b});
            setTimeout(function() {
                a("#promo").remove()
            }, 200)
        }
//        a(window).load(function() {
//            window.scrollTo(0, 1)
//        });
        var k = 0, l = 320, m = 0, j = 50, i = 100, n = false;
        g();

        a("body").bind("orientationchange", g);
        if (a.cookie("promoClose") != "close" && (navigator.userAgent.toLowerCase().match("iphone") || navigator.userAgent.toLowerCase().match("ipod")) && navigator.userAgent.toLowerCase().match("safari")) {
            a("body").append('<div id="promo"><a href="http://itunes.apple.com/ru/app/id463487053" id="ad">Download the iPhone App</a><a href="#" id="pclose">Close Ad</a></div>');
            document.body.ontouchmove = function() {
                s()
            };
            document.body.ontouchend = function() {
                setTimeout(function() {
                    o()
                }, 300)
            };
            setTimeout(function() {
                o()
            }, 2E3);
            setTimeout(function() {
                p()
            }, 2E4);
            a("a#pclose").live("click", function() {
                p();
                a.cookie("promoClose", "close", {expires: 7,path: "/",domain: "be-in.ru"});
                return false
            })
        }
    })
})(jQuery);
;if($.browser.msie /*&& $.browser.version < parseInt(9)*/) {
    $(function(){
        $('.cool_button.link table td').click(function(){
            var href=$(this).closest('a').attr('href');
            window.location.href=href;
        });
    });
};
