if (!window.VK) window.VK = {};

/*
 * easyXDM
 * http://easyxdm.net/
 * Copyright(c) 2009, Oyvind Sean Kinsey, oyvind@kinsey.no.
 *
 * MIT Licensed - http://easyxdm.net/license/mit.txt
 *
 */
 (function(E,c,j,D,g,B){var a=this;var i=0;var l=Function.prototype;var I=/^(http.?:\/\/([^\/\s]+))/,J=/[\-\w]+\/\.\.\//,z=/([^:])\/\//g;var M="easyXDM_";var b=/msie /.test(navigator.userAgent.toLowerCase());function x(O,Q){var P=typeof O[Q];return P=="function"||(!!(P=="object"&&O[Q]))||P=="unknown"}function p(O,P){return !!(typeof(O[P])=="object"&&O[P])}var q,t;if(x(E,"addEventListener")){q=function(Q,O,P){Q.addEventListener(O,P,false)};t=function(R,P,Q,O){R.removeEventListener(P,Q,O)}}else{if(x(E,"attachEvent")){q=function(O,Q,P){O.attachEvent("on"+Q,P)};t=function(O,Q,P){O.detachEvent("on"+Q,P)}}else{throw new Error("Browser not supported")}}var n=false,C=[];if("readyState" in c){n=(c.readyState=="complete"||c.readyState=="loaded")}else{if(c.body){n=true}}function m(){if(n){return}n=true;for(var O=0;O<C.length;O++){C[O]()}C.length=0;t(E,"DOMContentLoaded",m);t(c,"DOMContentLoaded",m);if(x(E,"ActiveXObject")){t(E,"load",m)}}function k(){if(c.readyState=="complete"){m();t(c,"readystatechange",k)}}if(!n){q(E,"DOMContentLoaded",m);q(c,"DOMContentLoaded",m);if(x(E,"ActiveXObject")){q(c,"readystatechange",k);q(E,"load",m);if(E===top){(function d(){if(n){return}try{c.documentElement.doScroll("left")}catch(O){D(d,1);return}m()}())}}}function A(P,O){if(n){P.call(O);return}C.push(function(){P.call(O)})}function u(O){return O.match(I)[2]}function f(O){return O.match(I)[1]}function w(O){O=O.replace(z,"$1/");if(!O.match(/^(http||https):\/\//)){var P=(O.substring(0,1)==="/")?"":j.pathname;if(P.substring(P.length-1)!=="/"){P=P.substring(0,P.lastIndexOf("/")+1)}O=j.protocol+"//"+j.host+P+O}while(J.test(O)){O=O.replace(J,"")}return O}function G(O,R){var T="",Q=O.indexOf("#");if(Q!==-1){T=O.substring(Q);O=O.substring(0,Q)}var S=[];for(var P in R){if(R.hasOwnProperty(P)){S.push(P+"="+B(R[P]))}}return O+((O.indexOf("?")===-1)?"?":"&")+S.join("&")+T}var K=(function(){var Q={},R,P=j.search.substring(1).split("&"),O=P.length;while(O--){R=P[O].split("=");if(R[0]!="title"){Q[R[0]]=g(R[1])}}return Q}());function o(O){return typeof O==="undefined"}var e=null;function F(){var P={};var Q={a:[1,2,3]},O='{"a":[1,2,3]}';if(E.cacheJSON){return E.cacheJSON}if(JSON.encode&&!JSON.stringify){JSON.stringify=JSON.encode}if(JSON.decode&&!JSON.parse){JSON.parse=JSON.decode}if(JSON&&typeof JSON.stringify==="function"&&JSON.stringify(Q).replace((/\s/g),"")===O){e={stringify:JSON.stringify,parse:JSON.parse};return e}if(Object.toJSON){if(Object.toJSON(Q).replace((/\s/g),"")===O){P.stringify=Object.toJSON}}if(typeof String.prototype.evalJSON==="function"){Q=O.evalJSON();if(Q.a&&Q.a.length===3&&Q.a[2]===3){P.parse=function(R){return R.evalJSON()}}}if(P.stringify&&P.parse){F=function(){return P};return P}return null}function L(O,P,Q){var S;for(var R in P){if(P.hasOwnProperty(R)){if(R in O){S=P[R];if(typeof S==="object"){L(O[R],S,Q)}else{if(!Q){O[R]=P[R]}}}else{O[R]=P[R]}}}return O}function v(O){var P;if(O.props.name&&b){P=c.createElement('<iframe name="'+O.props.name+'"/>')}else{P=c.createElement("IFRAME")}if(O.props.name){P.id=P.name=O.props.name;delete O.props.name}if(O.onLoad){P.loadFn=function(){O.onLoad(P.contentWindow)};q(P,"load",P.loadFn)}if(typeof O.container=="string"){O.container=c.getElementById(O.container)}if(!O.container){P.style.position="absolute";P.style.left="-2000px";P.style.top="0px";O.container=c.body}P.border=P.frameBorder=0;O.container.insertBefore(P,O.container.firstChild);L(P,O.props);return P}var H=(function(){if(x(E,"XMLHttpRequest")){return function(){return new XMLHttpRequest()}}else{var O=(function(){var Q=["Microsoft","Msxml2","Msxml3"],P=Q.length;while(P--){try{O=Q[P]+".XMLHTTP";var S=new ActiveXObject(O);return O}catch(R){}}}());return function(){return new ActiveXObject(O)}}}());function r(P){var R=H(),T=[],S,O;L(P,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","X-Requested-With":"XMLHttpRequest"},success:l,error:function(V){throw new Error(V)},data:{},type:"plain"},true);O=P.method=="POST";for(var Q in P.data){if(P.data.hasOwnProperty(Q)){T.push(B(Q)+"="+B(P.data[Q]))}}S=T.join("&");R.open(P.method,P.url+(O?"":"?"+S),true);for(var U in P.headers){if(P.headers.hasOwnProperty(U)){R.setRequestHeader(U,P.headers[U])}}R.onreadystatechange=function(){if(R.readyState==4){var V,W;if(P.type=="json"){try{V=R.responseText;V=F().parse(V)}catch(X){W="An error occured while parsing the JSON: "+X.message}}else{V=R.responseText}if(R.status<200||R.status>=300){W="The server did not return a valid status code."}if(W){P.error({message:W,status:R.status,data:V,toString:function(){return this.message+" Status: "+this.status}})}else{P.success(V)}R.onreadystatechange=l;R=null}};R.send(O?S:"")}function N(R,Q){if(typeof R=="string"){R=[R]}var P,O=R.length;while(O--){P=R[O];P=new RegExp(P.substr(0,1)=="^"?P:("^"+P.replace(/(\*)/g,".$1").replace(/\?/g,".")+"$"));if(P.test(Q)){return true}}return false}function h(Q){var V=Q.protocol,P;Q.isHost=Q.isHost||o(K.xdm_p);if(!Q.props){Q.props={}}if(!Q.isHost){Q.channel=K.xdm_c;Q.secret=K.xdm_s;Q.remote=K.xdm_e;V=K.xdm_p;if(Q.acl&&!N(Q.acl,Q.remote)){throw new Error("Access denied for "+Q.remote)}}else{Q.remote=w(Q.remote);Q.channel=Q.channel||"default"+i++;Q.secret=Math.random().toString(16).substring(2);if(o(V)){if(f(j.href)==f(Q.remote)){V="4"}else{if(navigator.userAgent.indexOf("Opera/9.5")==-1&&(x(E,"postMessage")||x(c,"postMessage"))){V="1"}else{if(x(E,"ActiveXObject")&&x(E,"execScript")){V="3"}else{if(navigator.product==="Gecko"&&"frameElement" in E&&navigator.userAgent.indexOf("WebKit")==-1){V="5"}else{if(Q.remoteHelper){Q.remoteHelper=w(Q.remoteHelper);V="2"}else{V="0"}}}}}}}switch(V){case"0":L(Q,{interval:100,delay:2000,useResize:true,useParent:false,usePolling:false},true);if(Q.isHost){if(!Q.local){var T=j.protocol+"//"+j.host,O=c.body.getElementsByTagName("img"),U;var R=O.length;while(R--){U=O[R];if(U.src.substring(0,T.length)===T){Q.local=U.src;break}}if(!Q.local){Q.local=E}}var S={xdm_c:Q.channel,xdm_p:0};if(Q.local===E){Q.usePolling=true;Q.useParent=true;Q.local=j.protocol+"//"+j.host+j.pathname+j.search;S.xdm_e=Q.local;S.xdm_pa=1}else{S.xdm_e=w(Q.local)}if(Q.container){Q.useResize=false;S.xdm_po=1}Q.remote=G(Q.remote,S)}else{L(Q,{channel:K.xdm_c,remote:K.xdm_e,useParent:!o(K.xdm_pa),usePolling:!o(K.xdm_po),useResize:Q.useParent?false:Q.useResize})}P=[new easyXDM.stack.HashTransport(Q),new easyXDM.stack.ReliableBehavior({}),new easyXDM.stack.QueueBehavior({encode:true,maxLength:4000-Q.remote.length}),new easyXDM.stack.VerifyBehavior({initiate:Q.isHost})];break;case"1":P=[new easyXDM.stack.PostMessageTransport(Q)];break;case"2":P=[new easyXDM.stack.NameTransport(Q),new easyXDM.stack.QueueBehavior(),new easyXDM.stack.VerifyBehavior({initiate:Q.isHost})];break;case"3":P=[new easyXDM.stack.NixTransport(Q)];break;case"4":P=[new easyXDM.stack.SameOriginTransport(Q)];break;case"5":P=[new easyXDM.stack.FrameElementTransport(Q)];break}P.push(new easyXDM.stack.QueueBehavior({lazy:Q.lazy,remove:true}));return P}function y(R){var S,Q={incoming:function(U,T){this.up.incoming(U,T)},outgoing:function(T,U){this.down.outgoing(T,U)},callback:function(T){this.up.callback(T)},init:function(){this.down.init()},destroy:function(){this.down.destroy()}};for(var P=0,O=R.length;P<O;P++){S=R[P];L(S,Q,true);if(P!==0){S.down=R[P-1]}if(P!==O-1){S.up=R[P+1]}}return S}function s(O){O.up.down=O.down;O.down.up=O.up;O.up=O.down=null}a.easyXDM={version:"2.4.6.17",query:K,stack:{},apply:L,ajax:r,getJSONObject:F,whenReady:A};easyXDM.DomHelper={on:q,un:t,requiresJSON:function(O){if(!p(E,"JSON")){c.write('<script type="text/javascript" src="'+O+'"><\/script>')}}};(function(){var O={};easyXDM.Fn={set:function(P,Q){O[P]=Q},get:function(Q,P){var R=O[Q];if(P){delete O[Q]}return R}}}());easyXDM.Socket=function(P){var O=y(h(P).concat([{incoming:function(S,R){P.onMessage(S,R)},callback:function(R){if(P.onReady){P.onReady(R)}}}])),Q=f(P.remote);this.destroy=function(){O.destroy()};this.postMessage=function(R){O.outgoing(R,Q)};O.init()};easyXDM.Rpc=function(Q,P){if(P.local){for(var S in P.local){if(P.local.hasOwnProperty(S)){var R=P.local[S];if(typeof R==="function"){P.local[S]={method:R}}}}}var O=y(h(Q).concat([new easyXDM.stack.RpcBehavior(this,P),{callback:function(T){if(Q.onReady){Q.onReady(T)}}}]));this.destroy=function(){O.destroy()};O.init()};easyXDM.stack.SameOriginTransport=function(P){var Q,S,R,O;return(Q={outgoing:function(U,V,T){R(U);if(T){T()}},destroy:function(){if(S){S.parentNode.removeChild(S);S=null}},onDOMReady:function(){O=f(P.remote);if(P.isHost){L(P.props,{src:G(P.remote,{xdm_e:j.protocol+"//"+j.host+j.pathname,xdm_c:P.channel,xdm_p:4}),name:M+P.channel+"_provider"});S=v(P);easyXDM.Fn.set(P.channel,function(T){R=T;D(function(){Q.up.callback(true)},0);return function(U){Q.up.incoming(U,O)}})}else{R=parent.easyXDM.Fn.get(P.channel,true)(function(T){Q.up.incoming(T,O)});Q.up.callback(true)}},init:function(){A(Q.onDOMReady,Q)}})};easyXDM.stack.PostMessageTransport=function(R){var T,U,P,Q;function O(V){if(V.origin){return V.origin}if(V.uri){return f(V.uri)}if(V.domain){return j.protocol+"//"+V.domain}throw"Unable to retrieve the origin of the event"}function S(W){var V=O(W);if(V==Q&&W.data.substring(0,R.channel.length+1)==R.channel+" "){T.up.incoming(W.data.substring(R.channel.length+1),V)}}return(T={outgoing:function(W,X,V){P.postMessage(R.channel+" "+W,X||Q);if(V){V()}},destroy:function(){t(E,"message",S);if(U){P=null;U.parentNode.removeChild(U);U=null}},onDOMReady:function(){Q=f(R.remote);if(R.isHost){q(E,"message",function V(W){if(W.data==R.channel+"-ready"){P=("postMessage" in U.contentWindow)?U.contentWindow:U.contentWindow.document;t(E,"message",V);q(E,"message",S);D(function(){T.up.callback(true)},0)}});L(R.props,{src:G(R.remote,{xdm_e:j.protocol+"//"+j.host,xdm_c:R.channel,xdm_p:1}),name:M+R.channel+"_provider"});U=v(R)}else{q(E,"message",S);P=("postMessage" in E.parent)?E.parent:E.parent.document;P.postMessage(R.channel+"-ready",Q);D(function(){T.up.callback(true)},0)}},init:function(){A(T.onDOMReady,T)}})};easyXDM.stack.FrameElementTransport=function(P){var Q,S,R,O;return(Q={outgoing:function(U,V,T){R.call(this,U);if(T){T()}},destroy:function(){if(S){S.parentNode.removeChild(S);S=null}},onDOMReady:function(){O=f(P.remote);if(P.isHost){L(P.props,{src:G(P.remote,{xdm_e:j.protocol+"//"+j.host+j.pathname+j.search,xdm_c:P.channel,xdm_p:5}),name:M+P.channel+"_provider"});S=v(P);S.fn=function(T){delete S.fn;R=T;D(function(){Q.up.callback(true)},0);return function(U){Q.up.incoming(U,O)}}}else{if(c.referrer&&c.referrer!=K.xdm_e){E.parent.location=K.xdm_e}else{if(c.referrer!=K.xdm_e){E.parent.location=K.xdm_e}R=E.frameElement.fn(function(T){Q.up.incoming(T,O)});Q.up.callback(true)}}},init:function(){A(Q.onDOMReady,Q)}})};easyXDM.stack.NixTransport=function(P){var R,T,S,O,Q;return(R={outgoing:function(V,W,U){S(V);if(U){U()}},destroy:function(){Q=null;if(T){T.parentNode.removeChild(T);T=null}},onDOMReady:function(){O=f(P.remote);if(P.isHost){try{if(!x(E,"getNixProxy")){E.execScript("Class NixProxy\n    Private m_parent, m_child, m_Auth\n\n    Public Sub SetParent(obj, auth)\n        If isEmpty(m_Auth) Then m_Auth = auth\n        SET m_parent = obj\n    End Sub\n    Public Sub SetChild(obj)\n        SET m_child = obj\n        m_parent.ready()\n    End Sub\n\n    Public Sub SendToParent(data, auth)\n        If m_Auth = auth Then m_parent.send(CStr(data))\n    End Sub\n    Public Sub SendToChild(data, auth)\n        If m_Auth = auth Then m_child.send(CStr(data))\n    End Sub\nEnd Class\nFunction getNixProxy()\n    Set GetNixProxy = New NixProxy\nEnd Function\n","vbscript")}Q=getNixProxy();Q.SetParent({send:function(W){R.up.incoming(W,O)},ready:function(){D(function(){R.up.callback(true)},0)}},P.secret);S=function(W){Q.SendToChild(W,P.secret)}}catch(V){throw new Error("Could not set up VBScript NixProxy:"+V.message)}L(P.props,{src:G(P.remote,{xdm_e:j.protocol+"//"+j.host+j.pathname+j.search,xdm_c:P.channel,xdm_s:P.secret,xdm_p:3}),name:M+P.channel+"_provider"});T=v(P);T.contentWindow.opener=Q}else{if(c.referrer!=K.xdm_e){}try{Q=E.opener}catch(U){throw new Error("Cannot access window.opener")}Q.SetChild({send:function(W){a.setTimeout(function(){R.up.incoming(W,O)},0)}});S=function(W){Q.SendToParent(W,P.secret)};D(function(){R.up.callback(true)},0)}},init:function(){A(R.onDOMReady,R)}})};easyXDM.stack.NameTransport=function(S){var T;var V,Z,R,X,Y,P,O;function W(ac){var ab=S.remoteHelper+(V?"#_3":"#_2")+S.channel;Z.contentWindow.sendMessage(ac,ab)}function U(){if(V){if(++X===2||!V){T.up.callback(true)}}else{W("ready");T.up.callback(true)}}function aa(ab){T.up.incoming(ab,P)}function Q(){if(Y){D(function(){Y(true)},0)}}return(T={outgoing:function(ac,ad,ab){Y=ab;W(ac)},destroy:function(){Z.parentNode.removeChild(Z);Z=null;if(V){R.parentNode.removeChild(R);R=null}},onDOMReady:function(){V=S.isHost;X=0;P=f(S.remote);S.local=w(S.local);if(V){easyXDM.Fn.set(S.channel,function(ab){if(V&&ab==="ready"){easyXDM.Fn.set(S.channel,aa);U()}});O=G(S.remote,{xdm_e:S.local,xdm_c:S.channel,xdm_p:2});L(S.props,{src:O+"#"+S.channel,name:M+S.channel+"_provider"});R=v(S)}else{S.remoteHelper=S.remote;easyXDM.Fn.set(S.channel,aa)}Z=v({props:{src:S.local+"#_4"+S.channel},onLoad:function(){t(Z,"load",Z.loadFn);easyXDM.Fn.set(S.channel+"_load",Q);(function ab(){if(typeof Z.contentWindow.sendMessage=="function"){U()}else{D(ab,50)}}())}})},init:function(){A(T.onDOMReady,T)}})};easyXDM.stack.HashTransport=function(Q){var T;var Y=this,W,R,O,U,ad,S,ac;var X,P;function ab(af){if(!ac){return}var ae=Q.remote+"#"+(ad++)+"_"+af;((W||!X)?ac.contentWindow:ac).location=ae}function V(ae){U=ae;T.up.incoming(U.substring(U.indexOf("_")+1),P)}function aa(){if(!S){return}var ae=S.location.href,ag="",af=ae.indexOf("#");if(af!=-1){ag=ae.substring(af)}if(ag&&ag!=U){V(ag)}}function Z(){R=setInterval(aa,O)}return(T={outgoing:function(ae,af){ab(ae)},destroy:function(){E.clearInterval(R);if(W||!X){ac.parentNode.removeChild(ac)}ac=null},onDOMReady:function(){W=Q.isHost;O=Q.interval;U="#"+Q.channel;ad=0;X=Q.useParent;P=f(Q.remote);if(W){Q.props={src:Q.remote,name:M+Q.channel+"_provider"};if(X){Q.onLoad=function(){S=E;Z();T.up.callback(true)}}else{var ag=0,ae=Q.delay/50;(function af(){if(++ag>ae){throw new Error("Unable to reference listenerwindow")}try{S=ac.contentWindow.frames[M+Q.channel+"_consumer"]}catch(ah){}if(S){Z();T.up.callback(true)}else{D(af,50)}}())}ac=v(Q)}else{S=E;Z();if(X){ac=parent;T.up.callback(true)}else{L(Q,{props:{src:Q.remote+"#"+Q.channel+new Date(),name:M+Q.channel+"_consumer"},onLoad:function(){T.up.callback(true)}});ac=v(Q)}}},init:function(){A(T.onDOMReady,T)}})};easyXDM.stack.ReliableBehavior=function(P){var R,T;var S=0,O=0,Q="";return(R={incoming:function(W,U){var V=W.indexOf("_"),X=W.substring(0,V).split(",");W=W.substring(V+1);if(X[0]==S){Q="";if(T){T(true)}}if(W.length>0){R.down.outgoing(X[1]+","+S+"_"+Q,U);if(O!=X[1]){O=X[1];R.up.incoming(W,U)}}},outgoing:function(W,U,V){Q=W;T=V;R.down.outgoing(O+","+(++S)+"_"+W,U)}})};easyXDM.stack.QueueBehavior=function(Q){var T,U=[],X=true,R="",W,O=0,P=false,S=false;function V(){if(Q.remove&&U.length===0){s(T);return}if(X||U.length===0||W){return}X=true;var Y=U.shift();T.down.outgoing(Y.data,Y.origin,function(Z){X=false;if(Y.callback){D(function(){Y.callback(Z)},0)}V()})}return(T={init:function(){if(o(Q)){Q={}}if(Q.maxLength){O=Q.maxLength;S=true}if(Q.lazy){P=true}else{T.down.init()}},callback:function(Z){X=false;var Y=T.up;V();Y.callback(Z)},incoming:function(ab,Z){if(S){var aa=ab.indexOf("_"),Y=parseInt(ab.substring(0,aa),10);R+=ab.substring(aa+1);if(Y===0){if(Q.encode){R=g(R)}T.up.incoming(R,Z);R=""}}else{T.up.incoming(ab,Z)}},outgoing:function(ac,Z,ab){if(Q.encode){ac=B(ac)}var Y=[],aa;if(S){while(ac.length!==0){aa=ac.substring(0,O);ac=ac.substring(aa.length);Y.push(aa)}while((aa=Y.shift())){U.push({data:Y.length+"_"+aa,origin:Z,callback:Y.length===0?ab:null})}}else{U.push({data:ac,origin:Z,callback:ab})}if(P){T.down.init()}else{V()}},destroy:function(){W=true;T.down.destroy()}})};easyXDM.stack.VerifyBehavior=function(S){var T,R,P,Q=false;function O(){R=Math.random().toString(16).substring(2);T.down.outgoing(R)}return(T={incoming:function(W,U){var V=W.indexOf("_");if(V===-1){if(W===R){T.up.callback(true)}else{if(!P){P=W;if(!S.initiate){O()}T.down.outgoing(W)}}}else{if(W.substring(0,V)===P){T.up.incoming(W.substring(V+1),U)}}},outgoing:function(W,U,V){T.down.outgoing(R+"_"+W,U,V)},callback:function(U){if(S.initiate){O()}}})};easyXDM.stack.RpcBehavior=function(U,P){var R,W=P.serializer||F();var V=0,T={};function O(X){X.jsonrpc="2.0";R.down.outgoing(W.stringify(X))}function S(X,Z){var Y=Array.prototype.slice;return function(){var aa=arguments.length,ac,ab={method:Z};if(aa>0&&typeof arguments[aa-1]==="function"){if(aa>1&&typeof arguments[aa-2]==="function"){ac={success:arguments[aa-2],error:arguments[aa-1]};ab.params=Y.call(arguments,0,aa-2)}else{ac={success:arguments[aa-1]};ab.params=Y.call(arguments,0,aa-1)}T[""+(++V)]=ac;ab.id=V}else{ab.params=Y.call(arguments,0)}O(ab)}}function Q(X,Z,ac,aa){if(!ac){if(Z){O({id:Z,error:{code:-32601,message:"Procedure not found."}})}return}var ae=false,ad,ab;if(Z){ad=function(ag){if(ae){return}ae=true;O({id:Z,result:ag})};ab=function(ag){if(ae){return}ae=true;var ah={id:Z,error:{code:-32099,message:"Application error: "+ag}};if(typeof ag=="object"&&"data" in ag){ah.error.data=ag.data}O(ah)}}else{ad=ab=l}try{var af=ac.method.apply(ac.scope,aa.concat([ad,ab]));if(!o(af)){ad(af)}}catch(Y){ab(Y.message)}}return(R={incoming:function(Y,X){var Z=W.parse(Y);if(Z.method){if(P.handle){P.handle(Z,O)}else{Q(Z.method,Z.id,P.local[Z.method],Z.params)}}else{var aa=T[Z.id];if(Z.error){if(aa.error){aa.error(Z.error)}}else{if(aa.success){aa.success(Z.result)}}delete T[Z.id]}},init:function(){if(P.remote){for(var X in P.remote){if(P.remote.hasOwnProperty(X)){U[X]=S(P.remote[X],X)}}}R.down.init()},destroy:function(){for(var X in P.remote){if(P.remote.hasOwnProperty(X)&&U.hasOwnProperty(X)){delete U[X]}}R.down.destroy()}})}})(window,document,location,window.setTimeout,decodeURIComponent,encodeURIComponent);

easyXDM.DomHelper.requiresJSON("http://vk.com/js/lib/json2.js");

/*
 * onDOMReady
 * Copyright (c) 2009 Ryan Morr (ryanmorr.com)
 * Licensed under the MIT license.
 */
if(!VK.onDOMReady) {
  VK.onDOMReady = function(fn,ctx){var ready,timer;var onStateChange=function(e){if(e&&e.type=="DOMContentLoaded"){fireDOMReady()}else if(e&&e.type=="load"){fireDOMReady()}else if(document.readyState){if((/loaded|complete/).test(document.readyState)){fireDOMReady()}else if(!!document.documentElement.doScroll){try{ready||document.documentElement.doScroll('left')}catch(e){return}fireDOMReady()}}};var fireDOMReady=function(){if(!ready){ready=true;fn.call(ctx||window);if(document.removeEventListener)document.removeEventListener("DOMContentLoaded",onStateChange,false);document.onreadystatechange=null;window.onload=null;clearInterval(timer);timer=null}};if(document.addEventListener)document.addEventListener("DOMContentLoaded",onStateChange,false);document.onreadystatechange=onStateChange;timer=setInterval(onStateChange,5);window.onload=onStateChange};
}


/*
 * Based on JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Copyright (C) Paul Johnston 1999 - 2009
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 */
if(!VK.MD5){VK.MD5=function(n){var j=function(o,r){var q=(o&65535)+(r&65535),p=(o>>16)+(r>>16)+(q>>16);return(p<<16)|(q&65535)},g=function(o,p){return(o<<p)|(o>>>(32-p))},k=function(w,r,p,o,v,u){return j(g(j(j(r,w),j(o,u)),v),p)},a=function(q,p,w,v,o,u,r){return k((p&w)|((~p)&v),q,p,o,u,r)},h=function(q,p,w,v,o,u,r){return k((p&v)|(w&(~v)),q,p,o,u,r)},c=function(q,p,w,v,o,u,r){return k(p^w^v,q,p,o,u,r)},m=function(q,p,w,v,o,u,r){return k(w^(p|(~v)),q,p,o,u,r)},b=function(A,u){var z=1732584193,y=-271733879,w=-1732584194,v=271733878,r,q,p,o;A[u>>5]|=128<<((u)%32);A[(((u+64)>>>9)<<4)+14]=u;for(var t=0,s=A.length;t<s;t+=16){r=z;q=y;p=w;o=v;z=a(z,y,w,v,A[t+0],7,-680876936);v=a(v,z,y,w,A[t+1],12,-389564586);w=a(w,v,z,y,A[t+2],17,606105819);y=a(y,w,v,z,A[t+3],22,-1044525330);z=a(z,y,w,v,A[t+4],7,-176418897);v=a(v,z,y,w,A[t+5],12,1200080426);w=a(w,v,z,y,A[t+6],17,-1473231341);y=a(y,w,v,z,A[t+7],22,-45705983);z=a(z,y,w,v,A[t+8],7,1770035416);v=a(v,z,y,w,A[t+9],12,-1958414417);w=a(w,v,z,y,A[t+10],17,-42063);y=a(y,w,v,z,A[t+11],22,-1990404162);z=a(z,y,w,v,A[t+12],7,1804603682);v=a(v,z,y,w,A[t+13],12,-40341101);w=a(w,v,z,y,A[t+14],17,-1502002290);y=a(y,w,v,z,A[t+15],22,1236535329);z=h(z,y,w,v,A[t+1],5,-165796510);v=h(v,z,y,w,A[t+6],9,-1069501632);w=h(w,v,z,y,A[t+11],14,643717713);y=h(y,w,v,z,A[t+0],20,-373897302);z=h(z,y,w,v,A[t+5],5,-701558691);v=h(v,z,y,w,A[t+10],9,38016083);w=h(w,v,z,y,A[t+15],14,-660478335);y=h(y,w,v,z,A[t+4],20,-405537848);z=h(z,y,w,v,A[t+9],5,568446438);v=h(v,z,y,w,A[t+14],9,-1019803690);w=h(w,v,z,y,A[t+3],14,-187363961);y=h(y,w,v,z,A[t+8],20,1163531501);z=h(z,y,w,v,A[t+13],5,-1444681467);v=h(v,z,y,w,A[t+2],9,-51403784);w=h(w,v,z,y,A[t+7],14,1735328473);y=h(y,w,v,z,A[t+12],20,-1926607734);z=c(z,y,w,v,A[t+5],4,-378558);v=c(v,z,y,w,A[t+8],11,-2022574463);w=c(w,v,z,y,A[t+11],16,1839030562);y=c(y,w,v,z,A[t+14],23,-35309556);z=c(z,y,w,v,A[t+1],4,-1530992060);v=c(v,z,y,w,A[t+4],11,1272893353);w=c(w,v,z,y,A[t+7],16,-155497632);y=c(y,w,v,z,A[t+10],23,-1094730640);z=c(z,y,w,v,A[t+13],4,681279174);v=c(v,z,y,w,A[t+0],11,-358537222);w=c(w,v,z,y,A[t+3],16,-722521979);y=c(y,w,v,z,A[t+6],23,76029189);z=c(z,y,w,v,A[t+9],4,-640364487);v=c(v,z,y,w,A[t+12],11,-421815835);w=c(w,v,z,y,A[t+15],16,530742520);y=c(y,w,v,z,A[t+2],23,-995338651);z=m(z,y,w,v,A[t+0],6,-198630844);v=m(v,z,y,w,A[t+7],10,1126891415);w=m(w,v,z,y,A[t+14],15,-1416354905);y=m(y,w,v,z,A[t+5],21,-57434055);z=m(z,y,w,v,A[t+12],6,1700485571);v=m(v,z,y,w,A[t+3],10,-1894986606);w=m(w,v,z,y,A[t+10],15,-1051523);y=m(y,w,v,z,A[t+1],21,-2054922799);z=m(z,y,w,v,A[t+8],6,1873313359);v=m(v,z,y,w,A[t+15],10,-30611744);w=m(w,v,z,y,A[t+6],15,-1560198380);y=m(y,w,v,z,A[t+13],21,1309151649);z=m(z,y,w,v,A[t+4],6,-145523070);v=m(v,z,y,w,A[t+11],10,-1120210379);w=m(w,v,z,y,A[t+2],15,718787259);y=m(y,w,v,z,A[t+9],21,-343485551);z=j(z,r);y=j(y,q);w=j(w,p);v=j(v,o)}return[z,y,w,v]},f=function(r){var q="",s=-1,p=r.length,o,t;while(++s<p){o=r.charCodeAt(s);t=s+1<p?r.charCodeAt(s+1):0;if(55296<=o&&o<=56319&&56320<=t&&t<=57343){o=65536+((o&1023)<<10)+(t&1023);s++}if(o<=127){q+=String.fromCharCode(o)}else{if(o<=2047){q+=String.fromCharCode(192|((o>>>6)&31),128|(o&63))}else{if(o<=65535){q+=String.fromCharCode(224|((o>>>12)&15),128|((o>>>6)&63),128|(o&63))}else{if(o<=2097151){q+=String.fromCharCode(240|((o>>>18)&7),128|((o>>>12)&63),128|((o>>>6)&63),128|(o&63))}}}}}return q},e=function(p){var o=Array(p.length>>2),r,q;for(r=0,q=o.length;r<q;r++){o[r]=0}for(r=0,q=p.length*8;r<q;r+=8){o[r>>5]|=(p.charCodeAt(r/8)&255)<<(r%32)}return o},l=function(p){var o="";for(var r=0,q=p.length*32;r<q;r+=8){o+=String.fromCharCode((p[r>>5]>>>(r%32))&255)}return o},d=function(o){return l(b(e(o),o.length*8))},i=function(q){var t="0123456789abcdef",p="",o;for(var s=0,r=q.length;s<r;s++){o=q.charCodeAt(s);p+=t.charAt((o>>>4)&15)+t.charAt(o&15)}return p};return i(d(f(n)))}};


/*
 * VKontakte Open API JavaScript library
 * http://vkontakte.ru/
 */
VK.extend = function(target, source, overwrite) {
  for (var key in source) {
    if (overwrite || typeof target[key] === 'undefined') {
      target[key] = source[key];
    }
  }
  return target;
};

VK.extend(VK, {
  _apiId: null,
  _session: null,
  _userStatus: 'unknown',
  _domain: {
    'main': window.location.protocol + '//vkontakte.ru/',
    'api': window.location.protocol + '//api.vkontakte.ru/api.php'
  },
  _path: {
    login: 'login.php',
//    proxy: 'xd_proxy_new.html',
    proxy: 'xd_proxy_new_debug.html',
    transport: 'xd_receiver.html',
    json: 'js/lib/json2.js'
  },
  _rootId: 'vk_api_transport',
  _nameTransportPath: '',
  xdReady: false,
  access: {
    FRIENDS:   0x2,
    PHOTOS:    0x4,
    AUDIO:     0x8,
    VIDEO:     0x10,
    MATCHES:   0x20,
    QUESTIONS: 0x40,
    WIKI:      0x80
  }
}, true);

VK.init = function(options) {
  var body, root;

  if (!options.apiId) {
    throw 'VK.init() called without an apiId'
  }
  VK._apiId = options.apiId;




  if (options.onlyWidgets) return true;

  if (options.nameTransportPath && options.nameTransportPath != '') {
    VK._nameTransportPath = options.nameTransportPath;
  }

  root = document.getElementById(VK._rootId);
  if (!root) {
    root = document.createElement('div');
    root.id = VK._rootId;
    body = document.getElementsByTagName('body')[0];
    body.insertBefore(root, body.childNodes[0]);
  }
  root.style.position = 'absolute';
  root.style.top = '-10000px';

  var session = VK.Cookie.load();
  if (session) {
    VK.Auth._loadState = 'loaded';
    VK.Auth.setSession(session, session ? 'connected' : 'unknown');
  }
  //this._lazyInit();
};

if(!VK.Cookie) {
  VK.Cookie = {
    _domain: null,
    load: function() {
      var
        cookie = document.cookie.match('\\bvk_app_' + VK._apiId + '=([^;]*)\\b'),
        session;

      if (cookie) {
        session = this.decode(cookie[1]);
        session.expire = parseInt(session.expire, 10);
        VK.Cookie._domain = '.' + window.location.hostname;//session.base_domain;
      }

      return session;
    },
    setRaw: function(val, ts, domain) {
      var
        rawCookie;

      rawCookie = 'vk_app_' + VK._apiId + '=' + val + '';
      rawCookie += (val && ts == 0 ? '' : '; expires=' + new Date(ts * 1000).toGMTString());
      rawCookie += '; path=/';
      rawCookie += (domain ? '; domain=.' + domain : '');
      document.cookie = rawCookie;

      this._domain = domain;
    },
    set: function(session) {
      session
        ? this.setRaw(this.encode(session), session.expire, window.location.hostname)
        : this.clear();
    },
    clear: function() {
      this.setRaw('', 0, this._domain);
    },
    encode: function(params) {
      var
        pairs = [],
        key;

      for(key in params) {
        if (key != 'user') pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(params[key]));
      }
      pairs.sort();

      return pairs.join('&');
    },
    decode: function(str) {
      var
        params = {},
        parts = str.split('&'),
        i,
        pair;

      for (i=0; i<parts.length; i++) {
        pair = parts[i].split('=', 2);
        if (pair && pair[0]) {
          params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
        }
      }

      return params;
    }
  }
}

if(!VK.Api) {
  VK.Api = {
    _headId: null,
    _callbacks: {},
    attachScript: function(url) {
      if (!VK.Api._headId) VK.Api._headId = document.getElementsByTagName("head")[0];
      var newScript = document.createElement('script');
      newScript.type = 'text/javascript';
      newScript.setAttribute('encoding', 'UTF-8');
      newScript.src = url;
      VK.Api._headId.appendChild(newScript);
    },
    call: function(method, params, cb, queryTry) {
      var
        query = params || {},
        qs,
        responseCb;

      if (typeof query != 'object' || typeof cb != 'function') {
        return false;
      }

      if (!queryTry) queryTry = 0;

      if (VK.Auth._loadState != 'loaded') {
        var authFunc = function(result) {
          if (result && result.session) {
            VK.Observer.unsubscribe('auth.loginStatus', authFunc);
            VK.Api.call(method, params, cb);
          }
        };
        VK.Observer.subscribe('auth.loginStatus', authFunc);
        VK.Auth.getLoginStatus();
        return;
      }


      VK.extend(query, {
        api_id: VK._apiId,
        v: '3.0',
        format: 'JSON',
        method: method
      }, true);

      if (VK.Api.queryLength(query) < 1500) {
        var useXDM = false;
        var rnd = parseInt(Math.random() * 10000000);
        while (VK.Api._callbacks[rnd]) { rnd = parseInt(Math.random() * 10000000); };
        query['callback'] = 'VK.Api._callbacks['+rnd+']';
      } else {
        var useXDM = true;
      }

      VK.extend(query, {
        sig: this.sign(query),
        sid: VK._session ? VK._session.sid : ''
      }, true);
      qs = VK.Cookie.encode(query);

      responseCb = function(response) {
        if (response.error && (response.error.error_code == 3 || response.error.error_code == 4 || response.error.error_code == 5)) {
          if (queryTry > 3) return false;
          var repeatCall = function(resp) {
            VK.Observer.unsubscribe('auth.sessionChange', repeatCall);
            delete params['sid'];
            delete params['sig'];
            if (resp.session) VK.Api.call(method, params, cb, queryTry + 1);
          }
          VK.Observer.subscribe('auth.sessionChange', repeatCall);
          VK.Auth.getLoginStatus();
        } else {
          cb(response);
        }
        if (!useXDM) delete VK.Api._callbacks[rnd];
      };

      if (useXDM) {
        if (VK.xdReady) {
          VK.XDM.remote.apiCall(qs, responseCb);
        } else {
          VK.Observer.subscribe('xdm.init', function() {VK.XDM.remote.apiCall(qs, responseCb);});
          VK.XDM.init();
        }
      } else {
        VK.Api._callbacks[rnd] = responseCb;
        VK.Api.attachScript(VK._domain.api+'?' + qs);
      }
    },
    sign: function(query) {
      var i, keys = [], sign;
      for(i in query) {
        keys.push(i.toString());
      }
      keys.sort();
      sign = VK._session ? VK._session.mid : 0;
      for(i=0; i<keys.length; i++) {
        sign += keys[i] + '=' + query[keys[i]];
      }
      sign += VK._session ? VK._session.secret : '';
      return VK.MD5(sign);
    },
    queryLength: function(query) {
      var len = 100; // sid + sig
      for (i in query) {
        len+=i.length + encodeURIComponent(query.i).length + 1;
      }
      return len;
    }
  }
};

// Alias
VK.api = function(method, params, cb) {VK.Api.call(method, params, cb);}

if(!VK.Auth) {
VK.Auth = {
  popup: null,
  lsCb: {},
  setSession: function(session, status, settings) {
    var
      login = !VK._session && session,
      logout = VK._session && !session,
      both = VK._session && session && VK._session.mid != session.mid,
      sessionChange = login || logout || (VK._session && session && VK._session.sid != session.sid),
      statusChange = status != VK._userStatus,
      response = {
        'session': session,
        'status': status,
        'settings': settings
      };

    VK._session = session;

    VK._userStatus = status;

    VK.Cookie.set(session);

    if (sessionChange || statusChange || both) {
      setTimeout(function() {
        if (statusChange) {
          VK.Observer.publish('auth.statusChange', response);
        }

        if (logout || both) {
          VK.Observer.publish('auth.logout', response);
        }

        if (login || both) {
          if (VK.xdReady) VK.XDM.remote.init(VK._apiId, session, status);
          VK.Observer.publish('auth.login', response);
        }

        if (sessionChange) {
          VK.Observer.publish('auth.sessionChange', response);
        }
      }, 0);
    }

    if(VK.UI.active && !VK.UI.active.closed) {
      try {
        VK.UI.active.close();
      } catch (e) {};
      VK.Observer.publish('auth.onLogin', response);
      VK.Observer.unsubscribe('auth.onLogin');
    }

    return response;
  },
  /* Public VK.Auth methods */
  login: function(cb, settings) {
    /* Call this ONLY ON A USER EVENT as it opens a popup */
    var channel, url;

    if(!VK._apiId) {
      return false;
    }

    channel = window.location.protocol + '//' + window.location.hostname;
    /*if (VK._nameTransportPath) {
      channel += VK._nameTransportPath;
    }*/

    //url = VK._domain.main + VK._path.login + '?app='+VK._apiId+'&layout=openapi&channel='+encodeURIComponent(channel);
    url = VK._domain.main + VK._path.login + '?app='+VK._apiId+'&layout=openapi';

    if(settings && parseInt(settings) > 0) {
      url += '&settings=' + settings;
    }

    VK.Observer.unsubscribe('auth.onLogin');
    VK.Observer.subscribe('auth.onLogin', cb);

    VK.UI.popup({
      width: 554,
      height: 287,
      url: url
    });

    var authCallback = function() {
      VK.Auth.getLoginStatus(function(resp) {
        VK.Observer.publish('auth.onLogin', resp);
      }, true);
    }

    VK.UI.popupOpened = true;
    var popupCheck = function() {
      if (!VK.UI.popupOpened) return false;
      try {
        if (!VK.UI.active['top']) {
          VK.UI.popupOpened = false;
          authCallback();
          return true;
        }
      } catch(e) {
        VK.UI.popupOpened = false;
        authCallback();
        return true;
      }
      setTimeout(popupCheck, 100);
    };

    setTimeout(popupCheck, 100);
  },
  /* Logout user from app, vkontakte.ru & login.vk.com */
  logout: function(cb) {
    var onLogout = function(resp) {
      VK.Observer.unsubscribe('auth.statusChange', onLogout);
      if (cb) cb(resp);
    }
    VK.Observer.subscribe('auth.statusChange', onLogout);
    if (VK._session && VK._session.sid) VK.Api.attachScript('http://login.vk.com/?act=openapi&aid='+parseInt(VK._apiId)+'&location=' + encodeURIComponent(window.location.hostname)+'&do_logout=1&sid='+VK._session.sid);
    VK.Cookie.clear();
  },
  /* Get current login status from session (sync) (not use on load time)*/
  getSession: function() {
    return VK._session;
  },
  /* Get current login status from vkontakte.ru (async) */
  getLoginStatus: function(cb, force) {
    if (!VK._apiId) {
      return;
    }

    if (cb) {
      if (!force && VK.Auth._loadState == 'loaded') {
        cb({status: VK._userStatus, session: VK._session});
        return;
      } else {
        VK.Observer.subscribe('auth.loginStatus', cb);
      }
    }

    if (!force && VK.Auth._loadState == 'loading') {
      return;
    }

    VK.Auth._loadState = 'loading';
    var rnd = parseInt(Math.random() * 10000000);
    while (VK.Auth.lsCb[rnd]) { rnd = parseInt(Math.random() * 10000000); };
    VK.Auth.lsCb[rnd] = function(response) {
      VK.Auth._loadState = 'loaded';
      if (response && response.auth) {
        var session = {mid: response.user.id, sid: response.sid, secret: response.secret, expire: response.expire, sig: response.sig};
        if (force) session['user'] = response.user;
        var status = 'connected';
      } else {
        var session = null;
        var status = 'unknown';
      }
      VK.Auth.setSession(session, status);
      VK.Observer.publish('auth.loginStatus', {session: session, status: status});
      VK.Observer.unsubscribe('auth.loginStatus');
    };
    // AttachScript here
    VK.Api.attachScript('http://login.vk.com/?act=openapi&aid='+parseInt(VK._apiId)+'&location=' + encodeURIComponent(window.location.hostname)+'&rnd='+rnd);
    //VK.Api.attachScript('http://oillarionov.cs7777.vkontakte.ru/login-vk.php?act=openapi&aid='+parseInt(VK._apiId)+'&location=' + encodeURIComponent(window.location.hostname)+'&rnd='+rnd);
  }
}
};

if (!VK.UI) {
  VK.UI = {
    active: null,
    _buttons: [],
    popup: function(options) {
      var
        screenX = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft,
        screenY = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop,
        outerWidth = typeof window.outerWidth != 'undefined' ? window.outerWidth : document.body.clientWidth,
        outerHeight = typeof window.outerHeight != 'undefined' ? window.outerHeight : (document.body.clientHeight - 22),
        width = options.width,
        height = options.height,
        left = parseInt(screenX + ((outerWidth - width) / 2), 10),
        top = parseInt(screenY + ((outerHeight - height) / 2.5), 10),
        features = (
          'width=' + width +
          ',height=' + height +
          ',left=' + left +
          ',top=' + top
        );
        this.active = window.open(options.url, 'vk_openapi', features);
    },
    button: function(el, handler) {
      var html = '';

      if (typeof el == 'string') {
        el = document.getElementById(el);
      }


      this._buttons.push(el);
      index = this._buttons.length - 1;

      html = (
        '<table cellspacing="0" cellpadding="0" id="openapi_UI_' + index + '" onmouseover="VK.UI._change(1, ' + index + ');" onmouseout="VK.UI._change(0, ' + index + ');" onmousedown="VK.UI._change(2, ' + index + ');" onmouseup="VK.UI._change(1, ' + index + ');" style="cursor: pointer; border: 0px; font-family: tahoma; font-size: 10px;"><tr style="vertical-align: middle"><td></td>' +
        '<td><div style="border: 1px solid #3b6798;"><div style="border: 1px solid #5c82ab; border-top-color: #7e9cbc; background-color: #6d8fb3; color: #fff; text-shadow: 0px 1px #45688E; height: 15px; padding: 2px 4px 0px 6px;">&#1042;&#1086;&#1081;&#1090;&#1080;</div></div></td>' +
        '<td><div style="background: url('+VK._domain.main+'images/btns.png) 0px -42px no-repeat; width: 21px; height: 21px"></div></td>' +
        '<td><div style="border: 1px solid #3b6798;"><div style="border: 1px solid #5c82ab; border-top-color: #7e9cbc; background-color: #6d8fb3; color: #fff; text-shadow: 0px 1px #45688E; height: 15px; padding: 2px 6px 0px 4px;">&#1050;&#1086;&#1085;&#1090;&#1072;&#1082;&#1090;&#1077;</div></div></td><td></td>' +
        '</tr></table>'
      );
      el.innerHTML = html;
      el.style.width = el.childNodes[0].offsetWidth + 'px';
    },
    _change: function(state, index) {
      var row = document.getElementById('openapi_UI_' + index).rows[0];
      var elems = [row.cells[1].firstChild.firstChild, row.cells[3].firstChild.firstChild];
      for (var i = 0; i < 2; ++i) {
         var elem = elems[i];
        if (state == 0) {
          elem.style.backgroundColor = '#6D8FB3';
          elem.style.borderTopColor = '#7E9CBC';
          elem.style.borderLeftColor = elem.style.borderRightColor = elem.style.borderBottomColor = '#5C82AB';
        } else if (state == 1) {
          elem.style.backgroundColor = '#84A1BF';
          elem.style.borderTopColor = '#92ACC7';
          elem.style.borderLeftColor = elem.style.borderRightColor = elem.style.borderBottomColor = '#7293B7';
        } else if (state == 2) {
          elem.style.backgroundColor = '#6688AD';
          elem.style.borderBottomColor = '#7495B8';
          elem.style.borderLeftColor = elem.style.borderRightColor = elem.style.borderTopColor = '#51779F';
        }
      }
      var elems = [row.cells[0].firstChild, row.cells[4].firstChild];
      for (var i = 0; i < 2; ++i) {
        var elem = elems[i];
        if (elem) {
          if (state == 0) {
            elem.style.backgroundPosition = '-21px -' + (42 + i * 21) + 'px';
          } else if (state == 1) {
            elem.style.backgroundPosition = '-23px -' + (42 + i * 21) + 'px';
          } else if (state == 2) {
            elem.style.backgroundPosition = '-25px -' + (42 + i * 21) + 'px';
          }
        }
      }
      if (state == 0 || state == 2) {
        row.cells[2].firstChild.style.backgroundPosition = '0px -42px';
      } else if (state == 1) {
        row.cells[2].firstChild.style.backgroundPosition = '0px -63px';
      }
    }
  };
}

if (!VK.XDM) {
  VK.XDM = {
    remote: null,
    init: function() {
      if (this.remote) return false;
      this.remote = new easyXDM.Rpc({
        local: VK._nameTransportPath,
        remote: VK._domain.api + VK._path.proxy,
        remoteHelper: VK._domain.api + VK._path.transport,
        container: document.getElementById(VK._rootId),
        onReady: function() {
          VK.XDM.remote.init(VK._apiId, VK._session, VK._userStatus);
          VK.xdReady = true;
          VK.Observer.publish('xdm.init');
        }
      }, {
        remote: {
          init: {
            isVoid: true
          },
          apiCall: {},
          getLoginStatus: {},
          logout: {}
        },
        local: {
          setSession: {
            isVoid: true,
            method: function(session, status) {
              VK.Auth.setSession(session, status);
            }
          },
          alert: {
            isVoid: true,
            method: function(text) {
              alert(text);
            }
          }
        }
      });
    },
    xdHandler: function(code) {
      try {
        eval('VK.' + code);
      } catch(e) {};
    }
  }
};

if (!VK.Observer) {
  VK.Observer = {
    _subscribers: function() {
      if (!this._subscribersMap) {
        this._subscribersMap = {};
      }
      return this._subscribersMap;
    },
    publish: function(eventName) {
      var
        args = Array.prototype.slice.call(arguments),
        eventName = args.shift(),
        subscribers = this._subscribers()[eventName],
        i, j;

      if (!subscribers) return;

      for (i = 0, j = subscribers.length; i < j; i++) {
        if(subscribers[i] != null) {
          subscribers[i].apply(this, args);
        }
      }
    },
    subscribe: function(eventName, handler) {
      var
        subscribers = this._subscribers();

      if(typeof handler != 'function') return false;

      if(!subscribers[eventName]) {
        subscribers[eventName] = [handler];
      } else {
        subscribers[eventName].push(handler);
      }
    },
    unsubscribe: function(eventName, handler) {
      var
        subscribers = this._subscribers()[eventName],
        i, j;

      if (!subscribers) return false;
      if (typeof handler == 'function') {
        for (i = 0, j = subscribers.length; i < j; i++) {
          if (subscribers[i] == handler) {
            subscribers[i] = null;
          }
        }
      } else {
        delete this._subscribers()[eventName];
      }
    }
  }
}


VK.Widgets = {};

VK.Widgets.count = 0;
VK.Widgets.RPC = {};

VK.Widgets.Group = function(objId, options, gid) {
  options = options || {};
  gid = parseInt(gid);
  var base_domain = options.base_domain || 'http://vkontakte.ru';
  if (!gid) throw Error('No group_id passed');

  VK.Widgets.count += 1;
  var widgetId = VK.Widgets.count;

  var width = parseInt(options.width);
  if (width) {
    width = Math.max(200, Math.min(10000, width));
  } else {
    width = 200;
  }

  var mode = (options.mode) ? '1' : '0';

  var url = base_domain+'/widget_groups.php?gid=' + gid + '&width=' + width + '&mode=' + mode;

  var obj = document.getElementById(objId);
  obj.style.height = '133px';
  obj.style.width = width  + 'px';
  //obj.style.border = '1px solid #bec8d3';
  obj.style.textAlign = 'center';
  obj.innerHTML = '<img id="vkwidget' + widgetId + '_uploader" style="background: none; border: none; position: absolute; padding: 0px; margin: 60px 0px 0px -'+(parseInt(width/2)+16)+'px;" src="http://vk.com/images/upload.gif" />';

  VK.Widgets.RPC[widgetId] = new easyXDM.Rpc({
    remote: url,
    local: VK._nameTransportPath,
    container: obj,
    props: {
      width: width,
      height: '100%',
      scrolling: 'no',
      id: 'vkwidget' + widgetId,
      style: {
        overflow: 'hidden'
      }
    },
    onReady: function() {
      document.getElementById('vkwidget' + widgetId + '_uploader').style.display = 'none';
    }
  }, {
    remote: {
        authorised: {
        },
        unauthorised: {
        }
    },
    local: {
        resize: function(e, cb) {
          obj.style.height = e + 'px';
          document.getElementById('vkwidget'+widgetId).style.height = e + 'px';
        },
        auth: function() {
          VK.Auth.login(
            null,
            1
          );
        },
        logout: function () {
          VK.Auth.logout(function () {
            VK.Widgets.RPC[widgetId].unauthorised();
          });
        },
        waitAuth: function() {
          var _tmp = function(response) {
            VK.Observer.unsubscribe('auth.login', _tmp);
            VK.Observer.unsubscribe('auth.sessionChange', _tmp);
            VK.Widgets.RPC[widgetId].authorised();
          };
          VK.Observer.subscribe('auth.login', _tmp);
          VK.Observer.subscribe('auth.sessionChange', _tmp);
        }
    }
  });
}

VK.Widgets.Comments = function(objId, options, page) {
  options = options || {};
  if (!VK._apiId) throw Error('VK not initialized. Please use VK.init');
  var base_domain = 'http://vkontakte.ru';
  page = parseInt(page || 0);

  VK.Widgets.count += 1;
  var widgetId = VK.Widgets.count;

  var url = base_domain+'/widget_comments.php?app=' + VK._apiId + '&page=' + page + '&limit=' + (!isNaN(parseInt(options.limit)) ? parseInt(options.limit) : 10) + '&url=' + encodeURIComponent(location.href)+'&title=' + encodeURIComponent(document.title);

  var obj = document.getElementById(objId);
  obj.style.height = '133px';
  var width = parseInt(options.width);
  if (width) {
    Math.max(450, Math.min(10000, width));
    width += 'px';
    obj.style.width = width;
  } else {
    width = '100%';
  }


  VK.Widgets.RPC[widgetId] = new easyXDM.Rpc({
    remote: url,
    local: VK._nameTransportPath,
    container: obj,
    props: {
      width: width,
      height: '100%',
      scrolling: 'no',
      id: 'vkwidget' + widgetId,
      style: {
        overflow: 'hidden'
      }
    },
    onReady: function() {
    }
  }, {
    remote: {
        authorised: {
        },
        unauthorised: {
        }
    },
    local: {
        resize: function(e, cb) {
          obj.style.height = e + 'px';
          document.getElementById('vkwidget'+widgetId).style.height = e + 'px';
        },
        auth: function() {
          VK.Auth.login(
            null,
            1
          );
        },
        logout: function () {
          VK.Auth.logout(function () {
            VK.Widgets.RPC[widgetId].unauthorised();
          });
        },
        waitAuth: function() {
          var _tmp = function(response) {
            VK.Observer.unsubscribe('auth.login', _tmp);
            VK.Observer.unsubscribe('auth.sessionChange', _tmp);
            VK.Widgets.RPC[widgetId].authorised();
          };
          VK.Observer.subscribe('auth.login', _tmp);
          VK.Observer.subscribe('auth.sessionChange', _tmp);
        }
    }
  });
}


VK.Widgets.Like = function(objId, options, page) {
  options = options || {};
  if (!VK._apiId) throw Error('VK not initialized. Please use VK.init');
  var base_domain = 'http://vkontakte.ru';
  page = parseInt(page || 0);

  VK.Widgets.count += 1;
  var widgetId = VK.Widgets.count;
  var ss = function (el, styles) {VK.extend(el.style, styles, true);}

  var url = base_domain+'/widget_like.php?app=' + VK._apiId + '&page=' + page + '&limit=' + (!isNaN(parseInt(options.limit)) ? parseInt(options.limit) : 10) + '&url=' + encodeURIComponent(location.href), pt = '', pd = '';
  if (options.pageTitle) {
    pt = options.pageTitle;
  } else {
    if (document.title) pt = document.title;
  }
  if (pt) url += '&title=' + encodeURIComponent(pt.substr(0, 80));
  if (options.pageDescription) {
    pd = options.pageDescription;
  } else {
    var metas = document.getElementsByTagName('meta');
    for (var i in metas) {
      if (metas[i].name && metas[i].name.toLowerCase() == 'description') {
        pd = encodeURIComponent(metas[i].content);
        break;
      }
    }
  }
  if (pd) url += '&descr=' + encodeURIComponent(pd.substr(0, 500));

  var obj = document.getElementById(objId);
  ss(obj, {height: '22px', position: 'relative'});
  var width = parseInt(options.width);
  if (width) {
    Math.max(450, Math.min(10000, width));
    width += 'px';
    obj.style.width = width;
  } else {
    width = '100%';
  }

  VK.Widgets.RPC[widgetId] = new easyXDM.Rpc({
    remote: url,
    local: VK._nameTransportPath,
    container: obj,
    props: {
      width: width,
      height: '100%',
      scrolling: 'no',
      id: 'vkwidget' + widgetId,
      style: {
        overflow: 'hidden',
        position: navigator.userAgent.match(/msie /i) ? 'static' : 'absolute',
        zIndex: 150
      }
    },
    onReady: function() {
    }
  }, {
    remote: {
      authorised: {},
      unauthorised: {}
    },
    local: {
      resize: function(e, cb) {
        //obj.style.height = e + 'px';
        //document.getElementById('vkwidget'+widgetId).style.height = e + 'px';
      },
      auth: function() {
        VK.Auth.login(
          null,
          1
        );
      },
      logout: function () {
        VK.Auth.logout(function () {
          VK.Widgets.RPC[widgetId].unauthorised();
        });
      },
      waitAuth: function() {
        var _tmp = function(response) {
          VK.Observer.unsubscribe('auth.login', _tmp);
          VK.Observer.unsubscribe('auth.sessionChange', _tmp);
          VK.Widgets.RPC[widgetId].authorised();
        };
        VK.Observer.subscribe('auth.login', _tmp);
        VK.Observer.subscribe('auth.sessionChange', _tmp);
      },
      initShare: function (shareData) {
        ifr = document.createElement('iframe');
        ifr.frameBorder = '0';
        ifr.scrolling = 'no';
        ifr.src = url + '&act=a_share_button';
        ss(ifr, {position: 'absolute', top: '21px', left: '-1px', padding: 0, display: 'none', border: '0', width: '160px', height: '26px', zIndex: 140, overflow: 'hidden'});
        obj.insertBefore(ifr, obj.firstChild);

        var isOver = false;
        var checkOver = function () {if (!isOver) ifr.style.display = 'none';}
        insFrame.onmouseover = ifr.onmouseover = function () {isOver = true;}
        insFrame.onmouseout = ifr.onmouseout = function () {
          isOver = false;
          setTimeout(checkOver, 400);
        }
      },
      showShare: function (size) {ifr.style.display = 'block';},
      hideShare: function () {ifr.style.display = 'none';}
    }
  });
  var ifr, idoc, iwin, insFrame = obj.getElementsByTagName('iframe')[0];
}



/* Init asynchronous library loading */
window.setTimeout(function() {

  if (window.vkAsyncInit) {
    vkAsyncInit();
  }
}, 0);
