﻿/* jQuery ColorBox 1.3.16 http://colorpowered.com/colorbox/ */
/* Patched by Vincent Courcelle to add dynamic iframe support */
(function (E,k,R) { var F={ transition: "elastic",speed: 300,width: false,initialWidth: "600",innerWidth: false,maxWidth: false,height: false,initialHeight: "450",innerHeight: false,maxHeight: false,scalePhotos: true,scrolling: true,inline: false,html: false,iframe: false,fastIframe: true,photo: false,href: false,title: false,rel: false,opacity: 0.9,preloading: true,current: "image {current} of {total}",previous: "previous",next: "next",close: "close",open: false,returnFocus: true,loop: true,slideshow: false,slideshowAuto: true,slideshowSpeed: 2500,slideshowStart: "start slideshow",slideshowStop: "stop slideshow",onOpen: false,onLoad: false,onComplete: false,onCleanup: false,onClosed: false,overlayClose: true,escKey: true,arrowKey: true },v="colorbox",O="cbox",Q=O+"_open",e=O+"_load",P=O+"_complete",s=O+"_cleanup",W=O+"_closed",i=O+"_purge",t=E.browser.msie&&!E.support.opacity,Z=t&&E.browser.version<7,V=O+"_IE6",M,aa,ab,d,C,o,b,L,c,U,I,j,h,n,r,S,q,N,x,y,X={},ac,l,g,a,u,D,m,A,T,H=false,G,p=O+"Element";function K(af,ad) { var ae=k.createElement("div");if(af) { ae.id=O+af } ae.style.cssText=ad||false;return E(ae) } function J(ad,ae) { ae=ae==="x"?U.width():U.height();return (typeof ad==="string")?Math.round((/%/.test(ad)?(ae/100)*parseInt(ad,10):parseInt(ad,10))):ad } function z(ad) { return X.photo||/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i.test(ad) } function Y(ae) { for(var ad in ae) { if(E.isFunction(ae[ad])&&ad.substring(0,2)!=="on") { ae[ad]=ae[ad].call(u) } } var af=E(u);ae.iframe=ae.iframe||af.attr("ColorBoxIframe")=="true";ae.width=ae.width||af.attr("ColorBoxWidth");ae.height=ae.height||af.attr("ColorBoxHeight");ae.rel=ae.rel||u.rel||"nofollow";ae.href=E.trim(ae.href||E(u).attr("href"));ae.title=ae.title||u.title } function B(ad,ae) { if(ae) { ae.call(u) } E.event.trigger(ad) } function w() { var ae,ag=O+"Slideshow_",ah="click."+O,ai,af,ad;if(X.slideshow&&c[1]) { ai=function () { S.text(X.slideshowStop).unbind(ah).bind(P,function () { if(D<c.length-1||X.loop) { ae=setTimeout(G.next,X.slideshowSpeed) } }).bind(e,function () { clearTimeout(ae) }).one(ah+" "+s,af);aa.removeClass(ag+"off").addClass(ag+"on");ae=setTimeout(G.next,X.slideshowSpeed) };af=function () { clearTimeout(ae);S.text(X.slideshowStart).unbind([P,e,s,ah].join(" ")).one(ah,ai);aa.removeClass(ag+"on").addClass(ag+"off") };if(X.slideshowAuto) { ai() } else { af() } } } function f(ad) { if(!H) { u=ad;Y(E.extend(X,E.data(u,v)));c=E(u);D=0;if(X.rel!=="nofollow") { c=E("."+p).filter(function () { var af=E.data(this,v).rel||this.rel;return (af===X.rel) });D=c.index(u);if(D=== -1) { c=c.add(u);D=c.length-1 } } if(!A) { A=T=true;aa.show();if(X.returnFocus) { try { u.blur();E(u).one(W,function () { try { this.focus() } catch(af) { } }) } catch(ae) { } } M.css({ opacity: +X.opacity,cursor: X.overlayClose?"pointer":"auto" }).show();X.w=J(X.initialWidth,"x");X.h=J(X.initialHeight,"y");G.position(0);if(Z) { U.bind("resize."+V+" scroll."+V,function () { M.css({ width: U.width(),height: U.height(),top: U.scrollTop(),left: U.scrollLeft() }) }).trigger("resize."+V) } B(Q,X.onOpen);y.add(n).hide();x.html(X.close).show() } G.load(true) } } G=E.fn[v]=E[v]=function (ad,ag) { var ae=this,af;if(!ae[0]&&ae.selector) { return ae } ad=ad||{};if(ag) { ad.onComplete=ag } if(!ae[0]||ae.selector===undefined) { ae=E("<a/>");ad.open=true } ae.each(function () { E.data(this,v,E.extend({},E.data(this,v)||F,ad));E(this).addClass(p) });af=ad.open;if(E.isFunction(af)) { af=af.call(ae) } if(af) { f(ae[0]) } return ae };G.init=function () { U=E(R);aa=K().attr({ id: v,"class": t?O+(Z?"IE6":"IE"):"" });M=K("Overlay",Z?"position:absolute":"").hide();ab=K("Wrapper");d=K("Content").append(I=K("LoadedContent","width:0; height:0; overflow:hidden"),h=K("LoadingOverlay").add(K("LoadingGraphic")),n=K("Title"),r=K("Current"),q=K("Next"),N=K("Previous"),S=K("Slideshow").bind(Q,w),x=K("Close"));ab.append(K().append(K("TopLeft"),C=K("TopCenter"),K("TopRight")),K(false,"clear:left").append(o=K("MiddleLeft"),d,b=K("MiddleRight")),K(false,"clear:left").append(K("BottomLeft"),L=K("BottomCenter"),K("BottomRight"))).children().children().css({ "float": "left" });j=K(false,"position:absolute; width:9999px; visibility:hidden; display:none");E("body").prepend(M,aa.append(ab,j));d.children().hover(function () { E(this).addClass("hover") },function () { E(this).removeClass("hover") }).addClass("hover");ac=C.height()+L.height()+d.outerHeight(true)-d.height();l=o.width()+b.width()+d.outerWidth(true)-d.width();g=I.outerHeight(true);a=I.outerWidth(true);aa.css({ "padding-bottom": ac,"padding-right": l }).hide();q.click(function () { G.next() });N.click(function () { G.prev() });x.click(function () { G.close() });y=q.add(N).add(r).add(S);d.children().removeClass("hover");E("."+p).live("click",function (ad) { if(!((ad.button!==0&&typeof ad.button!=="undefined")||ad.ctrlKey||ad.shiftKey||ad.altKey)) { ad.preventDefault();f(this) } });M.click(function () { if(X.overlayClose) { G.close() } });E(k).bind("keydown."+O,function (ae) { var ad=ae.keyCode;if(A&&X.escKey&&ad===27) { ae.preventDefault();G.close() } if(A&&X.arrowKey&&c[1]) { if(ad===37) { ae.preventDefault();N.click() } else { if(ad===39) { ae.preventDefault();q.click() } } } }) };G.remove=function () { aa.add(M).remove();E("."+p).die("click").removeData(v).removeClass(p) };G.position=function (ah,ae) { var ag,af=Math.max(k.documentElement.clientHeight-X.h-g-ac,0)/2+U.scrollTop(),ad=Math.max(U.width()-X.w-a-l,0)/2+U.scrollLeft();ag=(aa.width()===X.w+a&&aa.height()===X.h+g)?0:ah;ab[0].style.width=ab[0].style.height="9999px";function ai(aj) { C[0].style.width=L[0].style.width=d[0].style.width=aj.style.width;h[0].style.height=h[1].style.height=d[0].style.height=o[0].style.height=b[0].style.height=aj.style.height } aa.dequeue().animate({ width: X.w+a,height: X.h+g,top: af,left: ad },{ duration: ag,complete: function () { ai(this);T=false;ab[0].style.width=(X.w+a+l)+"px";ab[0].style.height=(X.h+g+ac)+"px";if(ae) { ae() } },step: function () { ai(this) } }) };G.resize=function (ad) { if(A) { ad=ad||{};if(ad.width) { X.w=J(ad.width,"x")-a-l } if(ad.innerWidth) { X.w=J(ad.innerWidth,"x") } I.css({ width: X.w });if(ad.height) { X.h=J(ad.height,"y")-g-ac } if(ad.innerHeight) { X.h=J(ad.innerHeight,"y") } if(!ad.innerHeight&&!ad.height) { var ae=I.wrapInner("<div style='overflow:auto'></div>").children();X.h=ae.height();ae.replaceWith(ae.children()) } I.css({ height: X.h });G.position(X.transition==="none"?0:X.speed) } };G.prep=function (af) { if(!A) { return } var ag=X.transition==="none"?0:X.speed;U.unbind("resize."+O);I.remove();I=K("LoadedContent").html(af);function ad() { X.w=X.w||I.width();X.w=X.mw&&X.mw<X.w?X.mw:X.w;return X.w } function ah() { X.h=X.h||I.height();X.h=X.mh&&X.mh<X.h?X.mh:X.h;return X.h } I.hide().appendTo(j.show()).css({ width: ad(),overflow: X.scrolling?"auto":"hidden" }).css({ height: ah() }).prependTo(d);j.hide();E(m).css({ "float": "none" });if(Z) { E("select").not(aa.find("select")).filter(function () { return this.style.visibility!=="hidden" }).css({ visibility: "hidden" }).one(s,function () { this.style.visibility="inherit" }) } function ae(ai) { G.position(ai,function () { var ao,ap,am,al,an=c.length,ak,aj;if(!A) { return } aj=function () { h.hide();B(P,X.onComplete) };if(t) { if(m) { I.fadeIn(100) } } n.html(X.title).add(I).show();if(an>1) { if(typeof X.current==="string") { r.html(X.current.replace(/\{current\}/,D+1).replace(/\{total\}/,an)).show() } q[(X.loop||D<an-1)?"show":"hide"]().html(X.next);N[(X.loop||D)?"show":"hide"]().html(X.previous);ao=D?c[D-1]:c[an-1];am=D<an-1?c[D+1]:c[0];if(X.slideshow) { S.show() } if(X.preloading) { al=E.data(am,v).href||am.href;ap=E.data(ao,v).href||ao.href;al=E.isFunction(al)?al.call(am):al;ap=E.isFunction(ap)?ap.call(ao):ap;if(z(al)) { E("<img/>")[0].src=al } if(z(ap)) { E("<img/>")[0].src=ap } } } else { y.hide() } if(X.iframe) { ak=E("<iframe/>").addClass(O+"Iframe")[0];if(X.fastIframe) { aj() } else { E(ak).load(aj) } ak.name=O+(+new Date());ak.src=X.href;if(!X.scrolling) { ak.scrolling="no" } if(t) { ak.frameBorder=0;ak.allowTransparency="true" } E(ak).appendTo(I).one(i,function () { ak.src="//about:blank" }) } else { aj() } if(X.transition==="fade") { aa.fadeTo(ag,1,function () { aa[0].style.filter="" }) } else { aa[0].style.filter="" } U.bind("resize."+O,function () { G.position(0) }) }) } if(X.transition==="fade") { aa.fadeTo(ag,0,function () { ae(0) }) } else { ae(ag) } };G.load=function (af) { var ae,ag,ad=G.prep;T=true;m=false;u=c[D];if(!af) { Y(E.extend(X,E.data(u,v))) } B(i);B(e,X.onLoad);X.h=X.height?J(X.height,"y")-g-ac:X.innerHeight&&J(X.innerHeight,"y");X.w=X.width?J(X.width,"x")-a-l:X.innerWidth&&J(X.innerWidth,"x");X.mw=X.w;X.mh=X.h;if(X.maxWidth) { X.mw=J(X.maxWidth,"x")-a-l;X.mw=X.w&&X.w<X.mw?X.w:X.mw } if(X.maxHeight) { X.mh=J(X.maxHeight,"y")-g-ac;X.mh=X.h&&X.h<X.mh?X.h:X.mh } ae=X.href;h.show();if(X.inline) { K().hide().insertBefore(E(ae)[0]).one(i,function () { E(this).replaceWith(I.children()) });ad(E(ae)) } else { if(X.iframe) { ad(" ") } else { if(X.html) { ad(X.html) } else { if(z(ae)) { E(m=new Image()).addClass(O+"Photo").error(function () { X.title=false;ad(K("Error").text("This image could not be loaded")) }).load(function () { var ah;m.onload=null;if(X.scalePhotos) { ag=function () { m.height-=m.height*ah;m.width-=m.width*ah };if(X.mw&&m.width>X.mw) { ah=(m.width-X.mw)/m.width;ag() } if(X.mh&&m.height>X.mh) { ah=(m.height-X.mh)/m.height;ag() } } if(X.h) { m.style.marginTop=Math.max(X.h-m.height,0)/2+"px" } if(c[1]&&(D<c.length-1||X.loop)) { m.style.cursor="pointer";m.onclick=function () { G.next() } } if(t) { m.style.msInterpolationMode="bicubic" } setTimeout(function () { ad(m) },1) });setTimeout(function () { m.src=ae },1) } else { if(ae) { j.load(ae,function (ai,ah,aj) { ad(ah==="error"?K("Error").text("Request unsuccessful: "+aj.statusText):E(this).contents()) }) } } } } } };G.next=function () { if(!T&&c[1]&&(D<c.length-1||X.loop)) { D=D<c.length-1?D+1:0;G.load() } };G.prev=function () { if(!T&&c[1]&&(D||X.loop)) { D=D?D-1:c.length-1;G.load() } };G.close=function () { if(A&&!H) { H=true;A=false;B(s,X.onCleanup);U.unbind("."+O+" ."+V);M.fadeTo(200,0);aa.stop().fadeTo(300,0,function () { aa.add(M).css({ opacity: 1,cursor: "auto" }).hide();B(i);I.remove();setTimeout(function () { H=false;B(W,X.onClosed) },1) }) } };G.element=function () { return E(u) };G.settings=F;E(G.init) } (jQuery,document,this));

/* Strophe http://code.stanziq.com/strophe/ */
var Base64=(function() { var keyStr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var obj={ encode: function(input) { var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;do { chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)) { enc3=enc4=64 } else { if(isNaN(chr3)) { enc4=64 } } output=output+keyStr.charAt(enc1)+keyStr.charAt(enc2)+keyStr.charAt(enc3)+keyStr.charAt(enc4) } while(i<input.length);return output },decode: function(input) { var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");do { enc1=keyStr.indexOf(input.charAt(i++));enc2=keyStr.indexOf(input.charAt(i++));enc3=keyStr.indexOf(input.charAt(i++));enc4=keyStr.indexOf(input.charAt(i++));chr1=(enc1<<2)|(enc2>>4);chr2=((enc2&15)<<4)|(enc3>>2);chr3=((enc3&3)<<6)|enc4;output=output+String.fromCharCode(chr1);if(enc3!=64) { output=output+String.fromCharCode(chr2) } if(enc4!=64) { output=output+String.fromCharCode(chr3) } } while(i<input.length);return output } };return obj })();var MD5=(function() { var hexcase=0;var b64pad="";var chrsz=8;var safe_add=function(x,y) { var lsw=(x&65535)+(y&65535);var msw=(x>>16)+(y>>16)+(lsw>>16);return (msw<<16)|(lsw&65535) };var bit_rol=function(num,cnt) { return (num<<cnt)|(num>>>(32-cnt)) };var str2binl=function(str) { var bin=[];var mask=(1<<chrsz)-1;for(var i=0;i<str.length*chrsz;i+=chrsz) { bin[i>>5]|=(str.charCodeAt(i/chrsz)&mask)<<(i%32) } return bin };var binl2str=function(bin) { var str="";var mask=(1<<chrsz)-1;for(var i=0;i<bin.length*32;i+=chrsz) { str+=String.fromCharCode((bin[i>>5]>>>(i%32))&mask) } return str };var binl2hex=function(binarray) { var hex_tab=hexcase?"0123456789ABCDEF":"0123456789abcdef";var str="";for(var i=0;i<binarray.length*4;i++) { str+=hex_tab.charAt((binarray[i>>2]>>((i%4)*8+4))&15)+hex_tab.charAt((binarray[i>>2]>>((i%4)*8))&15) } return str };var binl2b64=function(binarray) { var tab="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var str="";var triplet,j;for(var i=0;i<binarray.length*4;i+=3) { triplet=(((binarray[i>>2]>>8*(i%4))&255)<<16)|(((binarray[i+1>>2]>>8*((i+1)%4))&255)<<8)|((binarray[i+2>>2]>>8*((i+2)%4))&255);for(j=0;j<4;j++) { if(i*8+j*6>binarray.length*32) { str+=b64pad } else { str+=tab.charAt((triplet>>6*(3-j))&63) } } } return str };var md5_cmn=function(q,a,b,x,s,t) { return safe_add(bit_rol(safe_add(safe_add(a,q),safe_add(x,t)),s),b) };var md5_ff=function(a,b,c,d,x,s,t) { return md5_cmn((b&c)|((~b)&d),a,b,x,s,t) };var md5_gg=function(a,b,c,d,x,s,t) { return md5_cmn((b&d)|(c&(~d)),a,b,x,s,t) };var md5_hh=function(a,b,c,d,x,s,t) { return md5_cmn(b^c^d,a,b,x,s,t) };var md5_ii=function(a,b,c,d,x,s,t) { return md5_cmn(c^(b|(~d)),a,b,x,s,t) };var core_md5=function(x,len) { x[len>>5]|=128<<((len)%32);x[(((len+64)>>>9)<<4)+14]=len;var a=1732584193;var b= -271733879;var c= -1732584194;var d=271733878;var olda,oldb,oldc,oldd;for(var i=0;i<x.length;i+=16) { olda=a;oldb=b;oldc=c;oldd=d;a=md5_ff(a,b,c,d,x[i+0],7,-680876936);d=md5_ff(d,a,b,c,x[i+1],12,-389564586);c=md5_ff(c,d,a,b,x[i+2],17,606105819);b=md5_ff(b,c,d,a,x[i+3],22,-1044525330);a=md5_ff(a,b,c,d,x[i+4],7,-176418897);d=md5_ff(d,a,b,c,x[i+5],12,1200080426);c=md5_ff(c,d,a,b,x[i+6],17,-1473231341);b=md5_ff(b,c,d,a,x[i+7],22,-45705983);a=md5_ff(a,b,c,d,x[i+8],7,1770035416);d=md5_ff(d,a,b,c,x[i+9],12,-1958414417);c=md5_ff(c,d,a,b,x[i+10],17,-42063);b=md5_ff(b,c,d,a,x[i+11],22,-1990404162);a=md5_ff(a,b,c,d,x[i+12],7,1804603682);d=md5_ff(d,a,b,c,x[i+13],12,-40341101);c=md5_ff(c,d,a,b,x[i+14],17,-1502002290);b=md5_ff(b,c,d,a,x[i+15],22,1236535329);a=md5_gg(a,b,c,d,x[i+1],5,-165796510);d=md5_gg(d,a,b,c,x[i+6],9,-1069501632);c=md5_gg(c,d,a,b,x[i+11],14,643717713);b=md5_gg(b,c,d,a,x[i+0],20,-373897302);a=md5_gg(a,b,c,d,x[i+5],5,-701558691);d=md5_gg(d,a,b,c,x[i+10],9,38016083);c=md5_gg(c,d,a,b,x[i+15],14,-660478335);b=md5_gg(b,c,d,a,x[i+4],20,-405537848);a=md5_gg(a,b,c,d,x[i+9],5,568446438);d=md5_gg(d,a,b,c,x[i+14],9,-1019803690);c=md5_gg(c,d,a,b,x[i+3],14,-187363961);b=md5_gg(b,c,d,a,x[i+8],20,1163531501);a=md5_gg(a,b,c,d,x[i+13],5,-1444681467);d=md5_gg(d,a,b,c,x[i+2],9,-51403784);c=md5_gg(c,d,a,b,x[i+7],14,1735328473);b=md5_gg(b,c,d,a,x[i+12],20,-1926607734);a=md5_hh(a,b,c,d,x[i+5],4,-378558);d=md5_hh(d,a,b,c,x[i+8],11,-2022574463);c=md5_hh(c,d,a,b,x[i+11],16,1839030562);b=md5_hh(b,c,d,a,x[i+14],23,-35309556);a=md5_hh(a,b,c,d,x[i+1],4,-1530992060);d=md5_hh(d,a,b,c,x[i+4],11,1272893353);c=md5_hh(c,d,a,b,x[i+7],16,-155497632);b=md5_hh(b,c,d,a,x[i+10],23,-1094730640);a=md5_hh(a,b,c,d,x[i+13],4,681279174);d=md5_hh(d,a,b,c,x[i+0],11,-358537222);c=md5_hh(c,d,a,b,x[i+3],16,-722521979);b=md5_hh(b,c,d,a,x[i+6],23,76029189);a=md5_hh(a,b,c,d,x[i+9],4,-640364487);d=md5_hh(d,a,b,c,x[i+12],11,-421815835);c=md5_hh(c,d,a,b,x[i+15],16,530742520);b=md5_hh(b,c,d,a,x[i+2],23,-995338651);a=md5_ii(a,b,c,d,x[i+0],6,-198630844);d=md5_ii(d,a,b,c,x[i+7],10,1126891415);c=md5_ii(c,d,a,b,x[i+14],15,-1416354905);b=md5_ii(b,c,d,a,x[i+5],21,-57434055);a=md5_ii(a,b,c,d,x[i+12],6,1700485571);d=md5_ii(d,a,b,c,x[i+3],10,-1894986606);c=md5_ii(c,d,a,b,x[i+10],15,-1051523);b=md5_ii(b,c,d,a,x[i+1],21,-2054922799);a=md5_ii(a,b,c,d,x[i+8],6,1873313359);d=md5_ii(d,a,b,c,x[i+15],10,-30611744);c=md5_ii(c,d,a,b,x[i+6],15,-1560198380);b=md5_ii(b,c,d,a,x[i+13],21,1309151649);a=md5_ii(a,b,c,d,x[i+4],6,-145523070);d=md5_ii(d,a,b,c,x[i+11],10,-1120210379);c=md5_ii(c,d,a,b,x[i+2],15,718787259);b=md5_ii(b,c,d,a,x[i+9],21,-343485551);a=safe_add(a,olda);b=safe_add(b,oldb);c=safe_add(c,oldc);d=safe_add(d,oldd) } return [a,b,c,d] };var core_hmac_md5=function(key,data) { var bkey=str2binl(key);if(bkey.length>16) { bkey=core_md5(bkey,key.length*chrsz) } var ipad=new Array(16),opad=new Array(16);for(var i=0;i<16;i++) { ipad[i]=bkey[i]^909522486;opad[i]=bkey[i]^1549556828 } var hash=core_md5(ipad.concat(str2binl(data)),512+data.length*chrsz);return core_md5(opad.concat(hash),512+128) };var obj={ hexdigest: function(s) { return binl2hex(core_md5(str2binl(s),s.length*chrsz)) },b64digest: function(s) { return binl2b64(core_md5(str2binl(s),s.length*chrsz)) },hash: function(s) { return binl2str(core_md5(str2binl(s),s.length*chrsz)) },hmac_hexdigest: function(key,data) { return binl2hex(core_hmac_md5(key,data)) },hmac_b64digest: function(key,data) { return binl2b64(core_hmac_md5(key,data)) },hmac_hash: function(key,data) { return binl2str(core_hmac_md5(key,data)) },test: function() { return MD5.hexdigest("abc")==="900150983cd24fb0d6963f7d28e17f72" } };return obj })();if(!Function.prototype.bind) { Function.prototype.bind=function(obj) { var func=this;return function() { return func.apply(obj,arguments) } } } if(!Function.prototype.prependArg) { Function.prototype.prependArg=function(arg) { var func=this;return function() { var newargs=[arg];for(var i=0;i<arguments.length;i++) { newargs.push(arguments[i]) } return func.apply(this,newargs) } } } if(!Array.prototype.indexOf) { Array.prototype.indexOf=function(elt) { var len=this.length;var from=Number(arguments[1])||0;from=(from<0)?Math.ceil(from):Math.floor(from);if(from<0) { from+=len } for(;from<len;from++) { if(from in this&&this[from]===elt) { return from } } return -1 } } (function(callback) { var Strophe;function $build(name,attrs) { return new Strophe.Builder(name,attrs) } function $msg(attrs) { return new Strophe.Builder("message",attrs) } function $iq(attrs) { return new Strophe.Builder("iq",attrs) } function $pres(attrs) { return new Strophe.Builder("presence",attrs) } Strophe={ VERSION: "1.0.1",NS: { HTTPBIND: "http://jabber.org/protocol/httpbind",BOSH: "urn:xmpp:xbosh",CLIENT: "jabber:client",AUTH: "jabber:iq:auth",ROSTER: "jabber:iq:roster",PROFILE: "jabber:iq:profile",DISCO_INFO: "http://jabber.org/protocol/disco#info",DISCO_ITEMS: "http://jabber.org/protocol/disco#items",MUC: "http://jabber.org/protocol/muc",SASL: "urn:ietf:params:xml:ns:xmpp-sasl",STREAM: "http://etherx.jabber.org/streams",BIND: "urn:ietf:params:xml:ns:xmpp-bind",SESSION: "urn:ietf:params:xml:ns:xmpp-session",VERSION: "jabber:iq:version",STANZAS: "urn:ietf:params:xml:ns:xmpp-stanzas" },addNamespace: function(name,value) { Strophe.NS[name]=value },Status: { ERROR: 0,CONNECTING: 1,CONNFAIL: 2,AUTHENTICATING: 3,AUTHFAIL: 4,CONNECTED: 5,DISCONNECTED: 6,DISCONNECTING: 7,ATTACHED: 8 },LogLevel: { DEBUG: 0,INFO: 1,WARN: 2,ERROR: 3,FATAL: 4 },ElementType: { NORMAL: 1,TEXT: 3 },TIMEOUT: 1.1,SECONDARY_TIMEOUT: 0.1,forEachChild: function(elem,elemName,func) { var i,childNode;for(i=0;i<elem.childNodes.length;i++) { childNode=elem.childNodes[i];if(childNode.nodeType==Strophe.ElementType.NORMAL&&(!elemName||this.isTagEqual(childNode,elemName))) { func(childNode) } } },isTagEqual: function(el,name) { return el.tagName.toLowerCase()==name.toLowerCase() },_xmlGenerator: null,_makeGenerator: function() { var doc;if(window.ActiveXObject) { doc=new ActiveXObject("Microsoft.XMLDOM");doc.appendChild(doc.createElement("strophe")) } else { doc=document.implementation.createDocument("jabber:client","strophe",null) } return doc },xmlElement: function(name) { if(!name) { return null } var node=null;if(!Strophe._xmlGenerator) { Strophe._xmlGenerator=Strophe._makeGenerator() } node=Strophe._xmlGenerator.createElement(name);var a,i,k;for(a=1;a<arguments.length;a++) { if(!arguments[a]) { continue } if(typeof (arguments[a])=="string"||typeof (arguments[a])=="number") { node.appendChild(Strophe.xmlTextNode(arguments[a])) } else { if(typeof (arguments[a])=="object"&&typeof (arguments[a].sort)=="function") { for(i=0;i<arguments[a].length;i++) { if(typeof (arguments[a][i])=="object"&&typeof (arguments[a][i].sort)=="function") { node.setAttribute(arguments[a][i][0],arguments[a][i][1]) } } } else { if(typeof (arguments[a])=="object") { for(k in arguments[a]) { if(arguments[a].hasOwnProperty(k)) { node.setAttribute(k,arguments[a][k]) } } } } } } return node },xmlescape: function(text) { text=text.replace(/\&/g,"&amp;");text=text.replace(/</g,"&lt;");text=text.replace(/>/g,"&gt;");return text },xmlTextNode: function(text) { text=Strophe.xmlescape(text);if(!Strophe._xmlGenerator) { Strophe._xmlGenerator=Strophe._makeGenerator() } return Strophe._xmlGenerator.createTextNode(text) },getText: function(elem) { if(!elem) { return null } var str="";if(elem.childNodes.length===0&&elem.nodeType==Strophe.ElementType.TEXT) { str+=elem.nodeValue } for(var i=0;i<elem.childNodes.length;i++) { if(elem.childNodes[i].nodeType==Strophe.ElementType.TEXT) { str+=elem.childNodes[i].nodeValue } } return str },copyElement: function(elem) { var i,el;if(elem.nodeType==Strophe.ElementType.NORMAL) { el=Strophe.xmlElement(elem.tagName);for(i=0;i<elem.attributes.length;i++) { el.setAttribute(elem.attributes[i].nodeName.toLowerCase(),elem.attributes[i].value) } for(i=0;i<elem.childNodes.length;i++) { el.appendChild(Strophe.copyElement(elem.childNodes[i])) } } else { if(elem.nodeType==Strophe.ElementType.TEXT) { el=Strophe.xmlTextNode(elem.nodeValue) } } return el },escapeNode: function(node) { return node.replace(/^\s+|\s+$/g,"").replace(/\\/g,"\\5c").replace(/ /g,"\\20").replace(/\"/g,"\\22").replace(/\&/g,"\\26").replace(/\'/g,"\\27").replace(/\//g,"\\2f").replace(/:/g,"\\3a").replace(/</g,"\\3c").replace(/>/g,"\\3e").replace(/@/g,"\\40") },unescapeNode: function(node) { return node.replace(/\\20/g," ").replace(/\\22/g,'"').replace(/\\26/g,"&").replace(/\\27/g,"'").replace(/\\2f/g,"/").replace(/\\3a/g,":").replace(/\\3c/g,"<").replace(/\\3e/g,">").replace(/\\40/g,"@").replace(/\\5c/g,"\\") },getNodeFromJid: function(jid) { if(jid.indexOf("@")<0) { return null } return jid.split("@")[0] },getDomainFromJid: function(jid) { var bare=Strophe.getBareJidFromJid(jid);if(bare.indexOf("@")<0) { return bare } else { var parts=bare.split("@");parts.splice(0,1);return parts.join("@") } },getResourceFromJid: function(jid) { var s=jid.split("/");if(s.length<2) { return null } s.splice(0,1);return s.join("/") },getBareJidFromJid: function(jid) { return jid.split("/")[0] },log: function(level,msg) { return },debug: function(msg) { this.log(this.LogLevel.DEBUG,msg) },info: function(msg) { this.log(this.LogLevel.INFO,msg) },warn: function(msg) { this.log(this.LogLevel.WARN,msg) },error: function(msg) { this.log(this.LogLevel.ERROR,msg) },fatal: function(msg) { this.log(this.LogLevel.FATAL,msg) },serialize: function(elem) { var result;if(!elem) { return null } if(typeof (elem.tree)==="function") { elem=elem.tree() } var nodeName=elem.nodeName;var i,child;if(elem.getAttribute("_realname")) { nodeName=elem.getAttribute("_realname") } result="<"+nodeName;for(i=0;i<elem.attributes.length;i++) { if(elem.attributes[i].nodeName!="_realname") { result+=" "+elem.attributes[i].nodeName.toLowerCase()+"='"+elem.attributes[i].value.replace("&","&amp;").replace("'","&apos;").replace("<","&lt;")+"'" } } if(elem.childNodes.length>0) { result+=">";for(i=0;i<elem.childNodes.length;i++) { child=elem.childNodes[i];if(child.nodeType==Strophe.ElementType.NORMAL) { result+=Strophe.serialize(child) } else { if(child.nodeType==Strophe.ElementType.TEXT) { result+=child.nodeValue } } } result+="</"+nodeName+">" } else { result+="/>" } return result },_requestId: 0,_connectionPlugins: {},addConnectionPlugin: function(name,ptype) { Strophe._connectionPlugins[name]=ptype } };Strophe.Builder=function(name,attrs) { if(name=="presence"||name=="message"||name=="iq") { if(attrs&&!attrs.xmlns) { attrs.xmlns=Strophe.NS.CLIENT } else { if(!attrs) { attrs={ xmlns: Strophe.NS.CLIENT} } } } this.nodeTree=Strophe.xmlElement(name,attrs);this.node=this.nodeTree };Strophe.Builder.prototype={ tree: function() { return this.nodeTree },toString: function() { return Strophe.serialize(this.nodeTree) },up: function() { this.node=this.node.parentNode;return this },attrs: function(moreattrs) { for(var k in moreattrs) { if(moreattrs.hasOwnProperty(k)) { this.node.setAttribute(k,moreattrs[k]) } } return this },c: function(name,attrs) { var child=Strophe.xmlElement(name,attrs);this.node.appendChild(child);this.node=child;return this },cnode: function(elem) { this.node.appendChild(elem);this.node=elem;return this },t: function(text) { var child=Strophe.xmlTextNode(text);this.node.appendChild(child);return this } };Strophe.Handler=function(handler,ns,name,type,id,from,options) { this.handler=handler;this.ns=ns;this.name=name;this.type=type;this.id=id;this.options=options||{ matchbare: false };if(!this.options.matchBare) { this.options.matchBare=false } if(this.options.matchBare) { this.from=Strophe.getBareJidFromJid(from) } else { this.from=from } this.user=true };Strophe.Handler.prototype={ isMatch: function(elem) { var nsMatch;var from=null;if(this.options.matchBare) { from=Strophe.getBareJidFromJid(elem.getAttribute("from")) } else { from=elem.getAttribute("from") } nsMatch=false;if(!this.ns) { nsMatch=true } else { var self=this;Strophe.forEachChild(elem,null,function(elem) { if(elem.getAttribute("xmlns")==self.ns) { nsMatch=true } });nsMatch=nsMatch||elem.getAttribute("xmlns")==this.ns } if(nsMatch&&(!this.name||Strophe.isTagEqual(elem,this.name))&&(!this.type||elem.getAttribute("type")===this.type)&&(!this.id||elem.getAttribute("id")===this.id)&&(!this.from||from===this.from)) { return true } return false },run: function(elem) { var result=null;try { result=this.handler(elem) } catch(e) { if(e.sourceURL) { Strophe.fatal("error: "+this.handler+" "+e.sourceURL+":"+e.line+" - "+e.name+": "+e.message) } else { if(e.fileName) { if(typeof (console)!="undefined") { console.trace();console.error(this.handler," - error - ",e,e.message) } Strophe.fatal("error: "+this.handler+" "+e.fileName+":"+e.lineNumber+" - "+e.name+": "+e.message) } else { Strophe.fatal("error: "+this.handler) } } throw e } return result },toString: function() { return "{Handler: "+this.handler+"("+this.name+","+this.id+","+this.ns+")}" } };Strophe.TimedHandler=function(period,handler) { this.period=period;this.handler=handler;this.lastCalled=new Date().getTime();this.user=true };Strophe.TimedHandler.prototype={ run: function() { this.lastCalled=new Date().getTime();return this.handler() },reset: function() { this.lastCalled=new Date().getTime() },toString: function() { return "{TimedHandler: "+this.handler+"("+this.period+")}" } };Strophe.Request=function(elem,func,rid,sends) { this.id= ++Strophe._requestId;this.xmlData=elem;this.data=Strophe.serialize(elem);this.origFunc=func;this.func=func;this.rid=rid;this.date=NaN;this.sends=sends||0;this.abort=false;this.dead=null;this.age=function() { if(!this.date) { return 0 } var now=new Date();return (now-this.date)/1000 };this.timeDead=function() { if(!this.dead) { return 0 } var now=new Date();return (now-this.dead)/1000 };this.xhr=this._newXHR() };Strophe.Request.prototype={ getResponse: function() { var node=null;if(this.xhr.responseXML&&this.xhr.responseXML.documentElement) { node=this.xhr.responseXML.documentElement;if(node.tagName=="parsererror") { Strophe.error("invalid response received");Strophe.error("responseText: "+this.xhr.responseText);Strophe.error("responseXML: "+Strophe.serialize(this.xhr.responseXML));throw "parsererror" } } else { if(this.xhr.responseText) { Strophe.error("invalid response received");Strophe.error("responseText: "+this.xhr.responseText);Strophe.error("responseXML: "+Strophe.serialize(this.xhr.responseXML)) } } return node },_newXHR: function() { var xhr=null;if(window.XMLHttpRequest) { xhr=new XMLHttpRequest();if(xhr.overrideMimeType) { xhr.overrideMimeType("text/xml") } } else { if(window.ActiveXObject) { xhr=new ActiveXObject("Microsoft.XMLHTTP") } } xhr.onreadystatechange=this.func.prependArg(this);return xhr } };Strophe.Connection=function(service) { this.service=service;this.jid="";this.rid=Math.floor(Math.random()*4294967295);this.sid=null;this.streamId=null;this.do_session=false;this.do_bind=false;this.timedHandlers=[];this.handlers=[];this.removeTimeds=[];this.removeHandlers=[];this.addTimeds=[];this.addHandlers=[];this._idleTimeout=null;this._disconnectTimeout=null;this.authenticated=false;this.disconnecting=false;this.connected=false;this.errors=0;this.paused=false;this.hold=1;this.wait=60;this.window=5;this._data=[];this._requests=[];this._uniqueId=Math.round(Math.random()*10000);this._sasl_success_handler=null;this._sasl_failure_handler=null;this._sasl_challenge_handler=null;this._idleTimeout=setTimeout(this._onIdle.bind(this),100);for(var k in Strophe._connectionPlugins) { if(Strophe._connectionPlugins.hasOwnProperty(k)) { var ptype=Strophe._connectionPlugins[k];var F=function() { };F.prototype=ptype;this[k]=new F();this[k].init(this) } } };Strophe.Connection.prototype={ reset: function() { this.rid=Math.floor(Math.random()*4294967295);this.sid=null;this.streamId=null;this.do_session=false;this.do_bind=false;this.timedHandlers=[];this.handlers=[];this.removeTimeds=[];this.removeHandlers=[];this.addTimeds=[];this.addHandlers=[];this.authenticated=false;this.disconnecting=false;this.connected=false;this.errors=0;this._requests=[];this._uniqueId=Math.round(Math.random()*10000) },pause: function() { this.paused=true },resume: function() { this.paused=false },getUniqueId: function(suffix) { if(typeof (suffix)=="string"||typeof (suffix)=="number") { return ++this._uniqueId+":"+suffix } else { return ++this._uniqueId+"" } },connect: function(jid,pass,callback,wait,hold) { this.jid=jid;this.pass=pass;this.connect_callback=callback;this.disconnecting=false;this.connected=false;this.authenticated=false;this.errors=0;this.wait=wait||this.wait;this.hold=hold||this.hold;this.domain=Strophe.getDomainFromJid(this.jid);var body=this._buildBody().attrs({ to: this.domain,"xml:lang": "en",wait: this.wait,hold: this.hold,content: "text/xml; charset=utf-8",ver: "1.6","xmpp:version": "1.0","xmlns:xmpp": Strophe.NS.BOSH });this._changeConnectStatus(Strophe.Status.CONNECTING,null);this._requests.push(new Strophe.Request(body.tree(),this._onRequestStateChange.bind(this).prependArg(this._connect_cb.bind(this)),body.tree().getAttribute("rid")));this._throttledRequestHandler() },attach: function(jid,sid,rid,callback,wait,hold,wind) { this.jid=jid;this.sid=sid;this.rid=rid;this.connect_callback=callback;this.domain=Strophe.getDomainFromJid(this.jid);this.authenticated=true;this.connected=true;this.wait=wait||this.wait;this.hold=hold||this.hold;this.window=wind||this.window;this._changeConnectStatus(Strophe.Status.ATTACHED,null) },xmlInput: function(elem) { return },xmlOutput: function(elem) { return },rawInput: function(data) { return },rawOutput: function(data) { return },send: function(elem) { if(elem===null) { return } if(typeof (elem.sort)==="function") { for(var i=0;i<elem.length;i++) { this._queueData(elem[i]) } } else { if(typeof (elem.tree)==="function") { this._queueData(elem.tree()) } else { this._queueData(elem) } } this._throttledRequestHandler();clearTimeout(this._idleTimeout);this._idleTimeout=setTimeout(this._onIdle.bind(this),100) },flush: function() { clearTimeout(this._idleTimeout);this._onIdle() },sendIQ: function(elem,callback,errback,timeout) { var timeoutHandler=null;var that=this;if(typeof (elem.tree)==="function") { elem=elem.tree() } var id=elem.getAttribute("id");if(!id) { id=this.getUniqueId("sendIQ");elem.setAttribute("id",id) } var handler=this.addHandler(function(stanza) { if(timeoutHandler) { that.deleteTimedHandler(timeoutHandler) } var iqtype=stanza.getAttribute("type");if(iqtype==="result") { if(callback) { callback(stanza) } } else { if(iqtype==="error") { if(errback) { errback(stanza) } } else { throw { name: "StropheError",message: "Got bad IQ type of "+iqtype} } } },null,"iq",null,id);if(timeout) { timeoutHandler=this.addTimedHandler(timeout,function() { that.deleteHandler(handler);if(errback) { errback(null) } return false }) } this.send(elem);return id },_queueData: function(element) { if(element===null||!element.tagName||!element.childNodes) { throw { name: "StropheError",message: "Cannot queue non-DOMElement."} } this._data.push(element) },_sendRestart: function() { this._data.push("restart");this._throttledRequestHandler();clearTimeout(this._idleTimeout);this._idleTimeout=setTimeout(this._onIdle.bind(this),100) },addTimedHandler: function(period,handler) { var thand=new Strophe.TimedHandler(period,handler);this.addTimeds.push(thand);return thand },deleteTimedHandler: function(handRef) { this.removeTimeds.push(handRef) },addHandler: function(handler,ns,name,type,id,from,options) { var hand=new Strophe.Handler(handler,ns,name,type,id,from,options);this.addHandlers.push(hand);return hand },deleteHandler: function(handRef) { this.removeHandlers.push(handRef) },disconnect: function(reason) { this._changeConnectStatus(Strophe.Status.DISCONNECTING,reason);Strophe.info("Disconnect was called because: "+reason);if(this.connected) { this._disconnectTimeout=this._addSysTimedHandler(3000,this._onDisconnectTimeout.bind(this));this._sendTerminate() } },_changeConnectStatus: function(status,condition) { for(var k in Strophe._connectionPlugins) { if(Strophe._connectionPlugins.hasOwnProperty(k)) { var plugin=this[k];if(plugin.statusChanged) { try { plugin.statusChanged(status,condition) } catch(err) { Strophe.error(""+k+" plugin caused an exception changing status: "+err) } } } } if(this.connect_callback) { try { this.connect_callback(status,condition) } catch(e) { Strophe.error("User connection callback caused an exception: "+e) } } },_buildBody: function() { var bodyWrap=$build("body",{ rid: this.rid++,xmlns: Strophe.NS.HTTPBIND });if(this.sid!==null) { bodyWrap.attrs({ sid: this.sid }) } return bodyWrap },_removeRequest: function(req) { Strophe.debug("removing request");var i;for(i=this._requests.length-1;i>=0;i--) { if(req==this._requests[i]) { this._requests.splice(i,1) } } req.xhr.onreadystatechange=function() { };this._throttledRequestHandler() },_restartRequest: function(i) { var req=this._requests[i];if(req.dead===null) { req.dead=new Date() } this._processRequest(i) },_processRequest: function(i) { var req=this._requests[i];var reqStatus= -1;try { if(req.xhr.readyState==4) { reqStatus=req.xhr.status } } catch(e) { Strophe.error("caught an error in _requests["+i+"], reqStatus: "+reqStatus) } if(typeof (reqStatus)=="undefined") { reqStatus= -1 } var time_elapsed=req.age();var primaryTimeout=(!isNaN(time_elapsed)&&time_elapsed>Math.floor(Strophe.TIMEOUT*this.wait));var secondaryTimeout=(req.dead!==null&&req.timeDead()>Math.floor(Strophe.SECONDARY_TIMEOUT*this.wait));var requestCompletedWithServerError=(req.xhr.readyState==4&&(reqStatus<1||reqStatus>=500));if(primaryTimeout||secondaryTimeout||requestCompletedWithServerError) { if(secondaryTimeout) { Strophe.error("Request "+this._requests[i].id+" timed out (secondary), restarting") } req.abort=true;req.xhr.abort();req.xhr.onreadystatechange=function() { };this._requests[i]=new Strophe.Request(req.xmlData,req.origFunc,req.rid,req.sends);req=this._requests[i] } if(req.xhr.readyState===0) { Strophe.debug("request id "+req.id+"."+req.sends+" posting");req.date=new Date();try { req.xhr.open("POST",this.service,true) } catch(e2) { Strophe.error("XHR open failed.");if(!this.connected) { this._changeConnectStatus(Strophe.Status.CONNFAIL,"bad-service") } this.disconnect();return } var sendFunc=function() { req.xhr.send(req.data) };if(req.sends>1) { var backoff=Math.pow(req.sends,3)*1000;setTimeout(sendFunc,backoff) } else { sendFunc() } req.sends++;this.xmlOutput(req.xmlData);this.rawOutput(req.data) } else { Strophe.debug("_processRequest: "+(i===0?"first":"second")+" request has readyState of "+req.xhr.readyState) } },_throttledRequestHandler: function() { if(!this._requests) { Strophe.debug("_throttledRequestHandler called with undefined requests") } else { Strophe.debug("_throttledRequestHandler called with "+this._requests.length+" requests") } if(!this._requests||this._requests.length===0) { return } if(this._requests.length>0) { this._processRequest(0) } if(this._requests.length>1&&Math.abs(this._requests[0].rid-this._requests[1].rid)<this.window-1) { this._processRequest(1) } },_onRequestStateChange: function(func,req) { Strophe.debug("request id "+req.id+"."+req.sends+" state changed to "+req.xhr.readyState);if(req.abort) { req.abort=false;return } var reqStatus;if(req.xhr.readyState==4) { reqStatus=0;try { reqStatus=req.xhr.status } catch(e) { } if(typeof (reqStatus)=="undefined") { reqStatus=0 } if(this.disconnecting) { if(reqStatus>=400) { this._hitError(reqStatus);return } } var reqIs0=(this._requests[0]==req);var reqIs1=(this._requests[1]==req);if((reqStatus>0&&reqStatus<500)||req.sends>5) { this._removeRequest(req);Strophe.debug("request id "+req.id+" should now be removed") } if(reqStatus==200) { if(reqIs1||(reqIs0&&this._requests.length>0&&this._requests[0].age()>Math.floor(Strophe.SECONDARY_TIMEOUT*this.wait))) { this._restartRequest(0) } Strophe.debug("request id "+req.id+"."+req.sends+" got 200");func(req);this.errors=0 } else { Strophe.error("request id "+req.id+"."+req.sends+" error "+reqStatus+" happened");if(reqStatus===0||(reqStatus>=400&&reqStatus<600)||reqStatus>=12000) { this._hitError(reqStatus);if(reqStatus>=400&&reqStatus<500) { this._changeConnectStatus(Strophe.Status.DISCONNECTING,null);this._doDisconnect() } } } if(!((reqStatus>0&&reqStatus<10000)||req.sends>5)) { this._throttledRequestHandler() } } },_hitError: function(reqStatus) { this.errors++;Strophe.warn("request errored, status: "+reqStatus+", number of errors: "+this.errors);if(this.errors>4) { this._onDisconnectTimeout() } },_doDisconnect: function() { Strophe.info("_doDisconnect was called");this.authenticated=false;this.disconnecting=false;this.sid=null;this.streamId=null;this.rid=Math.floor(Math.random()*4294967295);if(this.connected) { this._changeConnectStatus(Strophe.Status.DISCONNECTED,null);this.connected=false } this.handlers=[];this.timedHandlers=[];this.removeTimeds=[];this.removeHandlers=[];this.addTimeds=[];this.addHandlers=[] },_dataRecv: function(req) { try { var elem=req.getResponse() } catch(e) { if(e!="parsererror") { throw e } this.disconnect("strophe-parsererror") } if(elem===null) { return } this.xmlInput(elem);this.rawInput(Strophe.serialize(elem));var i,hand;while(this.removeHandlers.length>0) { hand=this.removeHandlers.pop();i=this.handlers.indexOf(hand);if(i>=0) { this.handlers.splice(i,1) } } while(this.addHandlers.length>0) { this.handlers.push(this.addHandlers.pop()) } if(this.disconnecting&&this._requests.length===0) { this.deleteTimedHandler(this._disconnectTimeout);this._disconnectTimeout=null;this._doDisconnect();return } var typ=elem.getAttribute("type");var cond,conflict;if(typ!==null&&typ=="terminate") { cond=elem.getAttribute("condition");conflict=elem.getElementsByTagName("conflict");if(cond!==null) { if(cond=="remote-stream-error"&&conflict.length>0) { cond="conflict" } this._changeConnectStatus(Strophe.Status.CONNFAIL,cond) } else { this._changeConnectStatus(Strophe.Status.CONNFAIL,"unknown") } this.disconnect();return } var self=this;Strophe.forEachChild(elem,null,function(child) { var i,newList;newList=self.handlers;self.handlers=[];for(i=0;i<newList.length;i++) { var hand=newList[i];if(hand.isMatch(child)&&(self.authenticated||!hand.user)) { if(hand.run(child)) { self.handlers.push(hand) } } else { self.handlers.push(hand) } } }) },_sendTerminate: function() { Strophe.info("_sendTerminate was called");var body=this._buildBody().attrs({ type: "terminate" });if(this.authenticated) { body.c("presence",{ xmlns: Strophe.NS.CLIENT,type: "unavailable" }) } this.disconnecting=true;var req=new Strophe.Request(body.tree(),this._onRequestStateChange.bind(this).prependArg(this._dataRecv.bind(this)),body.tree().getAttribute("rid"));this._requests.push(req);this._throttledRequestHandler() },_connect_cb: function(req) { Strophe.info("_connect_cb was called");this.connected=true;var bodyWrap=req.getResponse();if(!bodyWrap) { return } this.xmlInput(bodyWrap);this.rawInput(Strophe.serialize(bodyWrap));var typ=bodyWrap.getAttribute("type");var cond,conflict;if(typ!==null&&typ=="terminate") { cond=bodyWrap.getAttribute("condition");conflict=bodyWrap.getElementsByTagName("conflict");if(cond!==null) { if(cond=="remote-stream-error"&&conflict.length>0) { cond="conflict" } this._changeConnectStatus(Strophe.Status.CONNFAIL,cond) } else { this._changeConnectStatus(Strophe.Status.CONNFAIL,"unknown") } return } if(!this.sid) { this.sid=bodyWrap.getAttribute("sid") } if(!this.stream_id) { this.stream_id=bodyWrap.getAttribute("authid") } var wind=bodyWrap.getAttribute("requests");if(wind) { this.window=parseInt(wind,10) } var hold=bodyWrap.getAttribute("hold");if(hold) { this.hold=parseInt(hold,10) } var wait=bodyWrap.getAttribute("wait");if(wait) { this.wait=parseInt(wait,10) } var do_sasl_plain=false;var do_sasl_digest_md5=false;var do_sasl_anonymous=false;var mechanisms=bodyWrap.getElementsByTagName("mechanism");var i,mech,auth_str,hashed_auth_str;if(mechanisms.length>0) { for(i=0;i<mechanisms.length;i++) { mech=Strophe.getText(mechanisms[i]);if(mech=="DIGEST-MD5") { do_sasl_digest_md5=true } else { if(mech=="PLAIN") { do_sasl_plain=true } else { if(mech=="ANONYMOUS") { do_sasl_anonymous=true } } } } } else { var body=this._buildBody();this._requests.push(new Strophe.Request(body.tree(),this._onRequestStateChange.bind(this).prependArg(this._connect_cb.bind(this)),body.tree().getAttribute("rid")));this._throttledRequestHandler();return } if(Strophe.getNodeFromJid(this.jid)===null&&do_sasl_anonymous) { this._changeConnectStatus(Strophe.Status.AUTHENTICATING,null);this._sasl_success_handler=this._addSysHandler(this._sasl_success_cb.bind(this),null,"success",null,null);this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null);this.send($build("auth",{ xmlns: Strophe.NS.SASL,mechanism: "ANONYMOUS" }).tree()) } else { if(Strophe.getNodeFromJid(this.jid)===null) { this._changeConnectStatus(Strophe.Status.CONNFAIL,"x-strophe-bad-non-anon-jid");this.disconnect() } else { if(do_sasl_digest_md5) { this._changeConnectStatus(Strophe.Status.AUTHENTICATING,null);this._sasl_challenge_handler=this._addSysHandler(this._sasl_challenge1_cb.bind(this),null,"challenge",null,null);this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null);this.send($build("auth",{ xmlns: Strophe.NS.SASL,mechanism: "DIGEST-MD5" }).tree()) } else { if(do_sasl_plain) { auth_str=Strophe.getBareJidFromJid(this.jid);auth_str=auth_str+"\u0000";auth_str=auth_str+Strophe.getNodeFromJid(this.jid);auth_str=auth_str+"\u0000";auth_str=auth_str+this.pass;this._changeConnectStatus(Strophe.Status.AUTHENTICATING,null);this._sasl_success_handler=this._addSysHandler(this._sasl_success_cb.bind(this),null,"success",null,null);this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null);hashed_auth_str=Base64.encode(auth_str);this.send($build("auth",{ xmlns: Strophe.NS.SASL,mechanism: "PLAIN" }).t(hashed_auth_str).tree()) } else { this._changeConnectStatus(Strophe.Status.AUTHENTICATING,null);this._addSysHandler(this._auth1_cb.bind(this),null,null,null,"_auth_1");this.send($iq({ type: "get",to: this.domain,id: "_auth_1" }).c("query",{ xmlns: Strophe.NS.AUTH }).c("username",{}).t(Strophe.getNodeFromJid(this.jid)).tree()) } } } } },_sasl_challenge1_cb: function(elem) { var attribMatch=/([a-z]+)=("[^"]+"|[^,"]+)(?:,|$)/;var challenge=Base64.decode(Strophe.getText(elem));var cnonce=MD5.hexdigest(Math.random()*1234567890);var realm="";var host=null;var nonce="";var qop="";var matches;this.deleteHandler(this._sasl_failure_handler);while(challenge.match(attribMatch)) { matches=challenge.match(attribMatch);challenge=challenge.replace(matches[0],"");matches[2]=matches[2].replace(/^"(.+)"$/,"$1");switch(matches[1]) { case "realm": realm=matches[2];break;case "nonce": nonce=matches[2];break;case "qop": qop=matches[2];break;case "host": host=matches[2];break } } var digest_uri="xmpp/"+this.domain;if(host!==null) { digest_uri=digest_uri+"/"+host } var A1=MD5.hash(Strophe.getNodeFromJid(this.jid)+":"+realm+":"+this.pass)+":"+nonce+":"+cnonce;var A2="AUTHENTICATE:"+digest_uri;var responseText="";responseText+="username="+this._quote(Strophe.getNodeFromJid(this.jid))+",";responseText+="realm="+this._quote(realm)+",";responseText+="nonce="+this._quote(nonce)+",";responseText+="cnonce="+this._quote(cnonce)+",";responseText+='nc="00000001",';responseText+='qop="auth",';responseText+="digest-uri="+this._quote(digest_uri)+",";responseText+="response="+this._quote(MD5.hexdigest(MD5.hexdigest(A1)+":"+nonce+":00000001:"+cnonce+":auth:"+MD5.hexdigest(A2)))+",";responseText+='charset="utf-8"';this._sasl_challenge_handler=this._addSysHandler(this._sasl_challenge2_cb.bind(this),null,"challenge",null,null);this._sasl_success_handler=this._addSysHandler(this._sasl_success_cb.bind(this),null,"success",null,null);this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null);this.send($build("response",{ xmlns: Strophe.NS.SASL }).t(Base64.encode(responseText)).tree());return false },_quote: function(str) { return '"'+str.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"' },_sasl_challenge2_cb: function(elem) { this.deleteHandler(this._sasl_success_handler);this.deleteHandler(this._sasl_failure_handler);this._sasl_success_handler=this._addSysHandler(this._sasl_success_cb.bind(this),null,"success",null,null);this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null);this.send($build("response",{ xmlns: Strophe.NS.SASL }).tree());return false },_auth1_cb: function(elem) { var iq=$iq({ type: "set",id: "_auth_2" }).c("query",{ xmlns: Strophe.NS.AUTH }).c("username",{}).t(Strophe.getNodeFromJid(this.jid)).up().c("password").t(this.pass);if(!Strophe.getResourceFromJid(this.jid)) { this.jid=Strophe.getBareJidFromJid(this.jid)+"/strophe" } iq.up().c("resource",{}).t(Strophe.getResourceFromJid(this.jid));this._addSysHandler(this._auth2_cb.bind(this),null,null,null,"_auth_2");this.send(iq.tree());return false },_sasl_success_cb: function(elem) { Strophe.info("SASL authentication succeeded.");this.deleteHandler(this._sasl_failure_handler);this._sasl_failure_handler=null;if(this._sasl_challenge_handler) { this.deleteHandler(this._sasl_challenge_handler);this._sasl_challenge_handler=null } this._addSysHandler(this._sasl_auth1_cb.bind(this),null,"stream:features",null,null);this._sendRestart();return false },_sasl_auth1_cb: function(elem) { var i,child;for(i=0;i<elem.childNodes.length;i++) { child=elem.childNodes[i];if(child.nodeName=="bind") { this.do_bind=true } if(child.nodeName=="session") { this.do_session=true } } if(!this.do_bind) { this._changeConnectStatus(Strophe.Status.AUTHFAIL,null);return false } else { this._addSysHandler(this._sasl_bind_cb.bind(this),null,null,null,"_bind_auth_2");var resource=Strophe.getResourceFromJid(this.jid);if(resource) { this.send($iq({ type: "set",id: "_bind_auth_2" }).c("bind",{ xmlns: Strophe.NS.BIND }).c("resource",{}).t(resource).tree()) } else { this.send($iq({ type: "set",id: "_bind_auth_2" }).c("bind",{ xmlns: Strophe.NS.BIND }).tree()) } } return false },_sasl_bind_cb: function(elem) { if(elem.getAttribute("type")=="error") { Strophe.info("SASL binding failed.");this._changeConnectStatus(Strophe.Status.AUTHFAIL,null);return false } var bind=elem.getElementsByTagName("bind");var jidNode;if(bind.length>0) { jidNode=bind[0].getElementsByTagName("jid");if(jidNode.length>0) { this.jid=Strophe.getText(jidNode[0]);if(this.do_session) { this._addSysHandler(this._sasl_session_cb.bind(this),null,null,null,"_session_auth_2");this.send($iq({ type: "set",id: "_session_auth_2" }).c("session",{ xmlns: Strophe.NS.SESSION }).tree()) } else { this.authenticated=true;this._changeConnectStatus(Strophe.Status.CONNECTED,null) } } } else { Strophe.info("SASL binding failed.");this._changeConnectStatus(Strophe.Status.AUTHFAIL,null);return false } },_sasl_session_cb: function(elem) { if(elem.getAttribute("type")=="result") { this.authenticated=true;this._changeConnectStatus(Strophe.Status.CONNECTED,null) } else { if(elem.getAttribute("type")=="error") { Strophe.info("Session creation failed.");this._changeConnectStatus(Strophe.Status.AUTHFAIL,null);return false } } return false },_sasl_failure_cb: function(elem) { if(this._sasl_success_handler) { this.deleteHandler(this._sasl_success_handler);this._sasl_success_handler=null } if(this._sasl_challenge_handler) { this.deleteHandler(this._sasl_challenge_handler);this._sasl_challenge_handler=null } this._changeConnectStatus(Strophe.Status.AUTHFAIL,null);return false },_auth2_cb: function(elem) { if(elem.getAttribute("type")=="result") { this.authenticated=true;this._changeConnectStatus(Strophe.Status.CONNECTED,null) } else { if(elem.getAttribute("type")=="error") { this._changeConnectStatus(Strophe.Status.AUTHFAIL,null);this.disconnect() } } return false },_addSysTimedHandler: function(period,handler) { var thand=new Strophe.TimedHandler(period,handler);thand.user=false;this.addTimeds.push(thand);return thand },_addSysHandler: function(handler,ns,name,type,id) { var hand=new Strophe.Handler(handler,ns,name,type,id);hand.user=false;this.addHandlers.push(hand);return hand },_onDisconnectTimeout: function() { Strophe.info("_onDisconnectTimeout was called");var req;while(this._requests.length>0) { req=this._requests.pop();req.abort=true;req.xhr.abort();req.xhr.onreadystatechange=function() { } } this._doDisconnect();return false },_onIdle: function() { var i,thand,since,newList;while(this.removeTimeds.length>0) { thand=this.removeTimeds.pop();i=this.timedHandlers.indexOf(thand);if(i>=0) { this.timedHandlers.splice(i,1) } } while(this.addTimeds.length>0) { this.timedHandlers.push(this.addTimeds.pop()) } var now=new Date().getTime();newList=[];for(i=0;i<this.timedHandlers.length;i++) { thand=this.timedHandlers[i];if(this.authenticated||!thand.user) { since=thand.lastCalled+thand.period;if(since-now<=0) { if(thand.run()) { newList.push(thand) } } else { newList.push(thand) } } } this.timedHandlers=newList;var body,time_elapsed;if(this.authenticated&&this._requests.length===0&&this._data.length===0&&!this.disconnecting) { Strophe.info("no requests during idle cycle, sending blank request");this._data.push(null) } if(this._requests.length<2&&this._data.length>0&&!this.paused) { body=this._buildBody();for(i=0;i<this._data.length;i++) { if(this._data[i]!==null) { if(this._data[i]==="restart") { body.attrs({ to: this.domain,"xml:lang": "en","xmpp:restart": "true","xmlns:xmpp": Strophe.NS.BOSH }) } else { body.cnode(this._data[i]).up() } } } delete this._data;this._data=[];this._requests.push(new Strophe.Request(body.tree(),this._onRequestStateChange.bind(this).prependArg(this._dataRecv.bind(this)),body.tree().getAttribute("rid")));this._processRequest(this._requests.length-1) } if(this._requests.length>0) { time_elapsed=this._requests[0].age();if(this._requests[0].dead!==null) { if(this._requests[0].timeDead()>Math.floor(Strophe.SECONDARY_TIMEOUT*this.wait)) { this._throttledRequestHandler() } } if(time_elapsed>Math.floor(Strophe.TIMEOUT*this.wait)) { Strophe.warn("Request "+this._requests[0].id+" timed out, over "+Math.floor(Strophe.TIMEOUT*this.wait)+" seconds since last activity");this._throttledRequestHandler() } } clearTimeout(this._idleTimeout);this._idleTimeout=setTimeout(this._onIdle.bind(this),100) } };if(callback) { callback(Strophe,$build,$msg,$iq,$pres) } })(function() { window.Strophe=arguments[0];window.$build=arguments[1];window.$msg=arguments[2];window.$iq=arguments[3];window.$pres=arguments[4] });
//document.write("<scr"+"ipt type='text/javascript' src='/Static/XMPP/strophe.js'></scr"+"ipt>");
/* Strophe pubsub plugin */
Strophe.addConnectionPlugin("pubsub",{ _connection: null,init: function(a) { this._connection=a;Strophe.addNamespace("PUBSUB","http://jabber.org/protocol/pubsub");Strophe.addNamespace("PUBSUB_SUBSCRIBE_OPTIONS",Strophe.NS.PUBSUB+"#subscribe_options");Strophe.addNamespace("PUBSUB_ERRORS",Strophe.NS.PUBSUB+"#errors");Strophe.addNamespace("PUBSUB_EVENT",Strophe.NS.PUBSUB+"#event");Strophe.addNamespace("PUBSUB_OWNER",Strophe.NS.PUBSUB+"#owner");Strophe.addNamespace("PUBSUB_AUTO_CREATE",Strophe.NS.PUBSUB+"#auto-create");Strophe.addNamespace("PUBSUB_PUBLISH_OPTIONS",Strophe.NS.PUBSUB+"#publish-options");Strophe.addNamespace("PUBSUB_NODE_CONFIG",Strophe.NS.PUBSUB+"#node_config");Strophe.addNamespace("PUBSUB_CREATE_AND_CONFIGURE",Strophe.NS.PUBSUB+"#create-and-configure");Strophe.addNamespace("PUBSUB_SUBSCRIBE_AUTHORIZATION",Strophe.NS.PUBSUB+"#subscribe_authorization");Strophe.addNamespace("PUBSUB_GET_PENDING",Strophe.NS.PUBSUB+"#get-pending");Strophe.addNamespace("PUBSUB_MANAGE_SUBSCRIPTIONS",Strophe.NS.PUBSUB+"#manage-subscriptions");Strophe.addNamespace("PUBSUB_META_DATA",Strophe.NS.PUBSUB+"#meta-data") },createNode: function(a,h,c,o,d) { var e=this._connection.getUniqueId("pubsubcreatenode");var g=$iq({ from: a,to: h,type: "set",id: e });var m=Strophe.xmlElement("configure",[]);var k=Strophe.xmlElement("x",[["xmlns","jabber:x:data"]]);var j=Strophe.xmlElement("field",[["var","FORM_TYPE"],["type","hidden"]]);var l=Strophe.xmlElement("value",[]);var n=Strophe.xmlTextNode(Strophe.NS.PUBSUB+"#node_config");l.appendChild(n);j.appendChild(l);k.appendChild(j);for(var f in o) { var b=o[f];k.appendChild(b) } if(o.length&&o.length!=0) { m.appendChild(k) } g.c("pubsub",{ xmlns: Strophe.NS.PUBSUB }).c("create",{ node: c }).up().cnode(m);this._connection.addHandler(d,null,"iq",null,e,null);this._connection.send(g.tree());return e },subscribe: function(c,j,e,p,b,f) { var o=this._connection.getUniqueId("subscribenode");var g=Strophe.xmlElement("options",[]);var l=Strophe.xmlElement("x",[["xmlns","jabber:x:data"]]);var k=Strophe.xmlElement("field",[["var","FORM_TYPE"],["type","hidden"]]);var m=Strophe.xmlElement("value",[]);var n=Strophe.xmlTextNode(Strophe.NS.PUBSUB_SUBSCRIBE_OPTIONS);m.appendChild(n);k.appendChild(m);l.appendChild(k);var a=$iq({ from: c,to: j,type: "set",id: o });if(p&&p.length&&p.length!==0) { for(var h=0;h<p.length;h++) { var d=p[h];l.appendChild(d) } g.appendChild(l);a.c("pubsub",{ xmlns: Strophe.NS.PUBSUB }).c("subscribe",{ node: e,jid: c }).up().cnode(g) } else { a.c("pubsub",{ xmlns: Strophe.NS.PUBSUB }).c("subscribe",{ node: e,jid: c }) } this._connection.addHandler(f,null,"iq",null,o,null);this._connection.addHandler(b,null,"message",null,null,null);this._connection.send(a.tree());return o },unsubscribe: function(c,a,e,f) { var b=this._connection.getUniqueId("unsubscribenode");var d=$iq({ from: c,to: a,type: "set",id: b });d.c("pubsub",{ xmlns: Strophe.NS.PUBSUB }).c("unsubscribe",{ node: e,jid: c });this._connection.addHandler(f,null,"iq",null,b,null);this._connection.send(d.tree());return b },publish: function(c,h,d,j,e) { var b=this._connection.getUniqueId("publishnode");var a=Strophe.xmlElement("publish",[["node",d],["jid",c]]);for(var g in j) { var m=Strophe.xmlElement("item",[]);var k=Strophe.xmlElement("entry",[]);var l=Strophe.xmlTextNode(j[g]);k.appendChild(l);m.appendChild(k);a.appendChild(m) } var f=$iq({ from: c,to: h,type: "set",id: b });f.c("pubsub",{ xmlns: Strophe.NS.PUBSUB }).cnode(a);this._connection.addHandler(e,null,"iq",null,b,null);this._connection.send(f.tree());return b },items: function(b,a,d,e,f) { var c=$iq({ from: b,to: a,type: "get" });c.c("pubsub",{ xmlns: Strophe.NS.PUBSUB }).c("items",{ node: d });return this._connection.sendIQ(c.tree(),e,f) } });
//document.write("<scr"+"ipt type='text/javascript' src='/Static/XMPP/strophe.pubsub.js'></scr"+"ipt>");

function handleAjaxResp(result)
{
	IdentificationId=result.d.NewSessionKey;
}

var userAccountActivated=true;
function placeBid(auctionId)
{
	if(UserId>0)
	{
		actionDone();
		var currentWalletAmount=getPageWalletAmount(WalletId);

		if(!userAccountActivated)
		{
			var selector="#AccountActivationRequired";
			var jButtonAction=jQuery(selector).find(".buttonAction");
			alertActionCancel(selector,jButtonAction.text(),jButtonAction.attr("href"));
			SafeTrackEvent("Bidding","BidNotPlaced","ACCOUNT_ACTIVATION_SOFT");
			return;
		}
		
		if(currentWalletAmount>=1)
		{
			var holdCssClass="Auction_status_HOLD";
			var waitingCssClass="Auction_status_WAITING_SERVER";

			var jAuction=jQuery("#Auction_"+auctionId);
			jAuction.addClass(holdCssClass);
			jAuction.addClass(waitingCssClass);

			var jPublicName=jAuction.find(".CurrentWinnerPublicName");
			var oldPublicName=jPublicName.html();
			jPublicName.text(PublicName);

			var timeLeft=-1;
			var timeLeftObject=getTimeLeftObject(auctionId);
			if(timeLeftObject!=null)
			{timeLeft=timeLeftObject.timeLeft;}

			jQuery.ajax({
				url: "/WebServices/BiddingWebService.asmx/PlaceBid",
				data: '{ "req": {"SessionKey": "'+IdentificationId+'","AuctionId": "'+auctionId+'","Locale": "'+Locale+'"} }',
				dataType: "json",
				success: function (result)
				{
					//debug("placeBid:");
					//debug(inspect(result.d,2));

					handleAjaxResp(result);

					if(result&&result.d&&result.d.Success)
					{
						updateWalletAmount(WalletId,CurrencyId);

						SafeTrackPage("/A/BidPlaced");
						SafeTrackEvent("Bidding","BidPlaced","Auction #"+auctionId);
						if(timeLeft>=0)
						{ SafeTrackEvent("Bidding","BidPlacedTimer","TimeLeft_"+timeLeft); }

						var sessionPlacedBidsCookieName="SessionPlacedBids";
						var sessionPlacedBids=jQuery.cookie(sessionPlacedBidsCookieName);
						sessionPlacedBids=(sessionPlacedBids?parseInt(sessionPlacedBids):0)+1;
						jQuery.cookie(sessionPlacedBidsCookieName,sessionPlacedBids,{ path: "/" });

						if(currentWalletAmount>=2)
						{
							if(sessionPlacedBids==3)
							{
								setTimeout(function ()
								{ alertMakeAutoBid("#AutoBidPopUp"); },3000);
							}
						}
						else
						{
							setTimeout(function ()
							{ alertGetChipsEmpty("#WalletNowEmptyPopUp"); },3000);

						}
					}
					else
					{
						//Error occured, you don't hold the auction!
						jAuction.removeClass(waitingCssClass);
						jAuction.removeClass(holdCssClass);
						jPublicName.text(oldPublicName);

						alertBidNotTaken("#BidNotTaken",(result&&result.d)?result.d.Status:null);
						SafeTrackEvent("Bidding","BidNotPlaced",(result&&result.d)?result.d.Status:"NETWORK");
					}
				}
			});
		}
		else
		{
			alertGetChipsEmpty("#WalletNotEnoughPopUp");
			SafeTrackEvent("Bidding","BidNotPlaced","WALLET_SOFT");
		}
	}
	else
	{ document.location.href="/Y/LogIn/"; }
}

function alertBidNotTaken(selector,status)
{
	var jAlert=jQuery(selector);

	jAlert.find(".reason").hide();
	if(!status)
	{status="NETWORK";}
	
	jAlert.find(".reason"+status).show();

	var buttons={};
	buttons[jAlert.find(".buttonCancel").text()]=function () { jAlert.dialog("close"); }

	showDialog(jAlert,{
		modal: true,
		buttons: buttons
	});
}
function alertGetChipsEmpty(selector)
{
	var jButtonAction=jQuery(selector).find(".buttonAction");
	alertActionCancel(selector,jButtonAction.text(),jButtonAction.attr("href"));
}
function alertMakeAutoBid(selector)
{
	var jButtonAction=jQuery(selector).find(".buttonAction");
	alertActionCancel(selector,jButtonAction.text(),jButtonAction.attr("href"));
}
function alertActionCancel(selector,linkText,linkUrl)
{
	var buttons={};
	if(linkText && linkUrl)
	{ buttons[linkText]=function () { document.location.href=linkUrl; } } 	//Need to do it this way, else the button gets "linkText" as text

	var jAlert=jQuery(selector);
	buttons[jAlert.find(".buttonCancel").text()]=function(){ jAlert.dialog("close"); }

	showDialog(jAlert,{
		modal: true,
		buttons: buttons
	});
}


//Maintain a timeout when users don't don't anything
var timeOutDate;
function actionDone()
{
	var date=new Date();
	date.setTime(date.getTime()+1000*60*30);	//30 minutes timeout
	timeOutDate=date;
}

var noTimeout=0;
function hasTimedout()
{
	try
	{
		//Save the no timeout in a session cookie
		if(window.location.hash=="#NoTimeout"||window.location.hash=="#NoXMPP")
		{
			jQuery.cookie("NoTimeout",1,{ path: "/" });
			noTimeout=1;
		}
		if(noTimeout==0)
		{
			noTimeout=-1;
			if(jQuery.cookie("NoTimeout")=="1")
			{ noTimeout=1; }
		}
	}
	catch(err)
	{ debug("hasTimedout exception: "+err); }
	
	return noTimeout!=1 && timeOutDate && timeOutDate<new Date();
}


var pageAuctionId=0;
var startGetAuctions=false;
var startGetBids=false;
var startGetBestBids=false;
var startGetBidsCounts=false;
var lastUpdateId=0;
var prizesAreExclusive=false;
var roundTripDelay= -1;
var isUnLoading=false;
function doStartPush()
{return startGetAuctions||startGetBids||startGetBestBids||startGetBidsCounts; }

function getEverything()
{
	if(lastUpdateId>0&&XMPPServer&&XMPPPushUser&&xmppPush)
	{
		//Keep retrying every 5 seconds in case we loose the XMPP connexion
		setTimeout("getEverything()",5000);
		return;
	}
	else if(!doStartPush())
	{ return; }

	var startDate=new Date().getTime();

	jQuery.ajax({
		url: "/WebServices/BiddingWebService.asmx/GetBiddingEverything",
		data: '{ "req": {"SessionKey":"'+IdentificationId+'","AuctionId":"'+pageAuctionId+'","GetAuctions":"'+startGetAuctions+'","GetBids":"'+startGetBids+'","GetBestBids":"'+startGetBestBids+'","GetBestBidders":"'+startGetBidsCounts+'","SinceUpdateId":"'+lastUpdateId+'","BidCurrencyId":"'+PaidCurrencyId+'","WalletCurrencyId":"'+CurrencyId+'","Locale":"'+Locale+'" } }',
		success: function (result)
		{
			setSuccess();

			if(roundTripDelay<0)
			{
				var endDate=new Date().getTime();
				roundTripDelay=Math.ceil((endDate-startDate)/1000);
				//debug("roundTripDelay="+roundTripDelay);
			}

			//debug("getEverything:");
			//debug(inspect(result.d,3));

			var continueInMs=1;
			if(result&&result.d)
			{
				lastUpdateId=result.d.LastUpdateId;
				handleAjaxResp(result);

				pushAuctions(result.d.Auctions,result.d.ServerTime);
				applyBids(result.d.Bids);
				applyBestBids(result.d.BestBids,result.d.ServerTime,true);
				applyBidsCounts(pageAuctionId,result.d.BidsCounts);
				hideMultiPrizes();
			}
			else
			{
				//Error occured, don't reload that fast!
				continueInMs=10000;
			}

			if(hasTimedout())
			{
				var buttons={};

				var jAlert=jQuery("#TimeoutPopUp");
				buttons[jAlert.find(".buttonCancel").text()]=function () { jAlert.dialog("close"); }

				//Timeout occured, ask the user if he is still alive

				showDialog(jAlert,{
					modal: true,
					buttons: buttons,
					close: function (event,ui)
					{
						actionDone();
						setTimeout("getEverything()",1);
						jQuery(this).dialog("destroy");
					}
				});
			}
			else
			{
				//Continue in a new thread
				setTimeout("getEverything()",continueInMs);
			}
		}
		,error: function (XMLHttpRequest,textStatus,errorThrown)
		{
			setError();
			debug("AJAX Network error: please check your connection.\r\nHere is the returned error: "+textStatus+" "+errorThrown);
			setTimeout("getEverything()",3000);	//Retry every 3 seconds
		}
	});
}

function getAuction(auctionId)
{
	jQuery.ajax({
		url: "/WebServices/BiddingWebService.asmx/GetAuction",
		data: '{ "req": {"SessionKey":"'+IdentificationId+'","AuctionId": "'+auctionId+'","Locale":"'+Locale+'"} }',
		success: function(result)
		{
			//debug("getAuction:");
			//debug(inspect(result.d,3));

			if(result&&result.d)
			{
				handleAjaxResp(result);

				updateAuction(result.d.Auction,true,result.d.ServerTime);
				
				//Auctions might have been added, deleted, ... so reapply the bids!
				applyBestBids(null,result.d.ServerTime,false);
			}
		}
	});
}

var oldAuctions=new Array();
var terminatedAuctions=new Array();
function pushAuctions(auctions,serverTime)
{
	if(auctions && auctions.length>0)
	{
		for(var i=0;i<auctions.length;i++)
		{ savePushedAuction(auctions[i]); }

		applyAuctions(null,serverTime);
		applyBestBids(null,serverTime,false);
	}
}
function pushAuction(auction,serverTime)
{
	if(auction)
	{
		savePushedAuction(auction);
		
		applyAuctions(null,serverTime);
		applyBestBids(null,serverTime,false);
	}
}
function savePushedAuction(auction)
{
	if(auction)
	{
		//oldAuctions is maintained by applyAuctions so can't ensure an associative array
		//Anyway, applyAuctions requires an iteration over the full array because it requires a non-associative array
		var auctionFound=false;
		for(var i=0;i<oldAuctions.length;i++)
		{
			var tmpAuction=oldAuctions[i];
			if(tmpAuction&&tmpAuction.Id==auction.Id)
			{
				oldAuctions[i]=auction;
				auctionFound=true;
				break;
			}
		}
		if(!auctionFound)
		{ oldAuctions.push(auction); }
	}
}

function isAuctionTerminatedRecently(auction,serverTime)
{
	if(auction.DateLastBidServerTime)
	{ return (serverTime-auction.DateLastBidServerTime)<displayTerminatedAuctionsWithInplayDuring; }
	return false;
}
function isAuctionImminent(auction,serverTime)
{return auction.Status=="PENDING"&&auction.DateStartServerTime-serverTime<=60*60*24;}
function applyAuctions(auctions,serverTime)
{
	if(auctions)
	{oldAuctions=auctions;}
	else
	{auctions=oldAuctions;}

	if(auctions)
	{
		var getAuctionWeight=function (auction)
		{
			auction.BlockType="UNKNOWN";

			//Higher = the first
			if(auction==null)
			{ return 0; }

			var commonWeight=-1/auction.Id;	//Defines who will be the first in cases of = cost

			if(auction.Status=="CANCELED" || ((auction.Status=="TERMINATED"||auction.Status=="PAID"||auction.Status=="REFUNDED") && !isAuctionTerminatedRecently(auction,serverTime)))
			{
				auction.BlockType="TERMINATED";
				return 10000000000+(auction.DateLastBid?auction.DateLastBid.getTime():0)+commonWeight;
			}
			if(auction.Status=="INPLAY"||auction.Status=="SUSPENDED"||auction.Status=="TERMINATED"||auction.Status=="PAID"||auction.Status=="REFUNDED"||isAuctionImminent(auction,serverTime))
			{
				auction.BlockType="INPLAY";
				return 10000000000000+auction.AuctionCost+commonWeight;
			}
			if(auction.Status=="PENDING")
			{
				//return -1*(auction.DateStart?auction.DateStart.getTime():0);
				auction.BlockType="PENDING";
				return 10000000+auction.AuctionCost+commonWeight;
			}

			return 0;
		};
	
		//Sort auctions, most expensive first (ie the first will be the "big" auction)
		var sortAuctionFunction=function(a,b) {
			//<0 => a<b
			//=0 => a=b
			//>0 => a>b

			return getAuctionWeight(b)-getAuctionWeight(a);
		};

		auctions.sort(sortAuctionFunction);

		var haveBig=false;
		for(var i=0;i<auctions.length;i++)
		{
			var auction=auctions[i];

			if(auction.BlockType=="TERMINATED")
			{terminatedAuctions[auction.Id]=auction;}
			else
			{
				//Prevent the first auction to be PENDING (IMMINENT) or not to be CanBeStar
				var isBig=!haveBig&&auction.CanBeStar&&(auction.Status=="INPLAY"||auction.Status=="SUSPENDED");
				haveBig=haveBig||isBig;

				updateAuction(auction,isBig,serverTime);
			}
		}


		var terminatedAuctionsSorted=terminatedAuctions.slice(0);	//.slice(0) required to properly duplicate the array and prevent the sort to be done on the associative array
		terminatedAuctionsSorted.sort(sortAuctionFunction);
		jQuery("#TerminatedAuctionBlock").empty();

		//Loop max 4 times (ie we don't expect to have more that 4 terminated auctions IN THE TERMINATED BLOCK -- terminated auctions in the INPLAY block are not included here!)
		for(var i=0;i<terminatedAuctionsSorted.length&&i<4;i++)
		{
			var auction=terminatedAuctionsSorted[i];
			updateAuction(auction,false,serverTime);
		}
	}
}

var auctionsDetails=new Array();
var displayTerminatedAuctionsWithInplayDuring=1800;
function updateAuction(auction,isBigAuction,serverTime)
{
	if(auction && (!pageAuctionId || pageAuctionId==auction.Id))
	{
		//debug("updateAuction "+auction.Id+" ("+auction.Status+")");
		
		//debug("updateAuction(Id="+auction.Id+",Status="+auction.Status+",isBigAuction="+isBigAuction+",serverTime="+serverTime+")");
		
		auctionsDetails[auction.Id]=auction;
		
		//This will be set by updateBid
		//if(auction.DateLastBidServerTime)
		//{ setAuctionTimer(auction.Id,auction.DateLastBidServerTime,serverTime); }
		
		if(auction.BidCurrencyId==PaidCurrencyId&&auction.WalletCurrencyId==CurrencyId&&(pageAuctionId==0||auction.Id==pageAuctionId))
		{
			var isImminent=isAuctionImminent(auction,serverTime);

			if(auction.DealAuction)
			{ setAuctionImminentTimer(auction.Id,auction.DateLastBidServerTime,serverTime); }
			else if(isImminent)
			{ setAuctionImminentTimer(auction.Id,auction.DateStartServerTime,serverTime); }

			//Get the current auction block
			var defaultContainer=pageAuctionId>0?"#BigAuctionBlock":"#AuctionBlock";

			var container=defaultContainer;
			if(isBigAuction)
			{ container="#BigAuctionBlock"; }
			else if(auction.Status=="PENDING" && !isImminent)
			{container="#PendingAuctionBlock";}
			else if(auction.Status=="TERMINATED" || auction.Status=="PAID" || auction.Status=="CANCELED" || auction.Status=="REFUNDED")
			{
				if(isAuctionTerminatedRecently(auction,serverTime))
				{ }	//Default container
				else
				{ container="#TerminatedAuctionBlock"; }
			}

			var jContainer=jQuery(container);

			//Allow failback if the BigAuctionBlock or TerminatedAuctionBlock doesn't exists (place the auction in the defaultContainer)
			if(container!=defaultContainer && jContainer.size()<=0)
			{
				container=defaultContainer;
				jContainer=jQuery(container);
			}
			
			var jAuctionBlock=jQuery("#Auction_"+auction.Id);
			var auctionBlockCreated=false;

			var setBlockValues=function (jBlock)
			{
				if(jBlock)
				{
					if(auction.DealAuction)
					{
						if(!jBlock.hasClass("Auction_DEALAUCTION"))
						{ jBlock.addClass("Auction_DEALAUCTION"); }
						jBlock.find(".CurrentPrice").text(auction.AuctionCost);

						if(auction.QuantityTotal>0)
						{
							var stock=Math.max(Math.min(Math.floor(auction.QuantityLeft/auction.QuantityTotal*100),100),0);
							jBlock.find("#AuctionProgressBar_"+auction.Id).progressbar().progressbar("option","value",stock);
							jBlock.find("#AuctionProgressBarText_"+auction.Id).find(".CurrentStockPercent").text(stock);
						}
						else
						{ jBlock.find(".ProgressBar,.ProgressBarText").hide(); }
					}
				}
			};

			if(jAuctionBlock.size()>0 && jContainer.find("#"+jAuctionBlock.get(0).id).size()>0)	//Auction block exists and is in this container
			{
				//Check if status changed
				
				//If status changed, then replace the element by a new one!
				if(!jAuctionBlock.hasClass("Auction_status_"+auction.Status))
				{
					//debug("replacing auction "+auction.Id);
					var jBlock=jQuery(getTemplateParsed(auction,serverTime,container,defaultContainer));
					setBlockValues(jBlock);

					jAuctionBlock.after(jBlock);
					jAuctionBlock.remove();
					auctionBlockCreated=true;
				}
				else
				{ setBlockValues(jAuctionBlock); }
			}
			else
			{
				//Auction doesn't exists in this container, create it!
				
				//Make sure the container exists before removing the old auction block and creating the new one! or this could lead to an auction block disapparance...
				//Allow creation only for INPLAY and PENDING and SUSPENDED auction (don't recreate PAID or TERMINATED auctions...)
				//Prevent "INVISIBLE" to show up, only allow statuses below
				if(jContainer.size()>0&&(pageAuctionId||auction.Status=="INPLAY"||auction.Status=="PENDING"||auction.Status=="SUSPENDED"||auction.Status=="TERMINATED"||auction.Status=="PAID"||auction.Status=="CANCELED"||auction.Status=="REFUNDED"))
				{
					//Remove it if it exists in another place
					jAuctionBlock.remove();

					var jBlock=jQuery(getTemplateParsed(auction,serverTime,container,defaultContainer));
					setBlockValues(jBlock);

					jContainer.append(jBlock);
					
					auctionBlockCreated=true;
				}
			}

			if(isImminent)
			{ jAuctionBlock.addClass("Auction_status_IMMINENT"); }
			else if(jAuctionBlock.hasClass("Auction_status_IMMINENT"))
			{ jAuctionBlock.removeClass("Auction_status_IMMINENT"); }

			if(auctionBlockCreated)
			{ jQuery("#AuctionProgressBar_"+auction.Id).progressbar(); }
		}
		else
		{
			//Auction doesn't fit for the current user, just remove it from the page
			jQuery("#Auction_"+auction.Id).remove();
		}

		if(auction.Status=="INPLAY")
		{ auctionsBidsDuration[auction.Id]=auction.BidTime; }
	}
}

function getTemplateParsed(auction,serverTime,container,defaultContainer)
{
	//Put the auction in its container
	//We are unlikely creating a lot of auctions, so don't cache the template to save memory
	var jTemplate=jQuery(container+"Template");

	//Allow failback if the Template doesn't exists (pending auctions...) (use the default template)
	if(container!=defaultContainer&&jTemplate.size()<=0)
	{ jTemplate=jQuery(defaultContainer+"Template"); }

	return jTemplate.parseTemplate({ "auction": auction,"serverTime": serverTime });
}

function applyBids(bids)
{
	if(bids && bids.length>0)
	{
		var bestBid=bids[0];
		var jContainer=jQuery(".Auction_"+bestBid.AuctionId);

		var reservePrice=parseFloat(jContainer.find("#ReservePrice").val());
		if(!isNaN(reservePrice)&&reservePrice>0&&reservePrice>bestBid.BidPrice)
		{
			if(!jContainer.hasClass("RESERVE"))
			{ jContainer.addClass("RESERVE"); }
		}
		else
		{ jContainer.removeClass("RESERVE"); }

		for(var i=0;i<bids.length;i++)
		{
			var rank=i+1;
			var bid=bids[i];

			var jElements=jContainer.find(".TimeRank.Rank"+rank);
			jElements.find(".PublicName").text(bid.PublicName);
			jElements.find(".UserId").text(bid.UserId);
			jElements.find(".Price").text(formatNumber(bid.BidPrice,2));
			jElements.removeClass("Nobody").parents(".Nobody").removeClass("Nobody");
		}
	}
}

var oldBids=new Array();
function pushBid(bid,serverTime)
{
	if(bid)
	{
		//Iterate over oldBids because oldBids is also managed by applyBestBids which doesn't require an ordered array...
		var oldBidFound=false;
		var bidSet=false;
		for(var i=0;i<oldBids.length;i++)
		{
			var tmpBid=oldBids[i];
			if(tmpBid && tmpBid.AuctionId==bid.AuctionId)
			{
				if(tmpBid.BidId<bid.BidId)
				{
					oldBids[i]=bid;
					bidSet=true;
				}
				oldBidFound=true;
				break;
			}
		}
		if(!oldBidFound)
		{
			oldBids.push(bid);
			bidSet=true;
		}

		updateBid(bid,serverTime,bidSet);
	}
}

var bestBids=new Array();
function applyBestBids(bids,serverTime,push)
{
	//Keep all the best bids to enable reapplication of them even if the server don't resend them to us (on terminated auctions for exemple)
	if(bids)
	{
		for(var i=0;i<bids.length;i++)
		{
			var bid=bids[i];
			if(!bestBids[bid.AuctionId] || (bid && bestBids[bid.AuctionId].BidId<bid.BidId))
			{bestBids[bid.AuctionId]=bid;}
		}
	}

	for(var key in bestBids)
	{ updateBid(bestBids[key],serverTime,push); }
	launchUpdateBidTimers();

	jQuery(".Auction").removeClass("Auction_status_LOADING");	//Always do this: the auction might have been recreated or so
}

var bidServerTimes=new Array();
var auctionBlinks=new Array();
function updateBid(bid,serverTime,doSetAuctionTimer)
{
	if(bid!=null)
	{
		var jAuction=jQuery("#Auction_"+bid.AuctionId);
		jAuction.removeClass("Auction_status_WAITING_SERVER");
		jAuction.removeClass("Auction_status_NOBIDDER");
		jAuction.find(".CurrentPrice").text(formatNumber(bid.BidPrice,2));
		jAuction.find(".CurrentWinnerPublicName").text(bid.PublicName);

		if(UserId>0&&bid.UserId==UserId)
		{ jAuction.addClass("Auction_status_HOLD"); }
		else
		{ jAuction.removeClass("Auction_status_HOLD"); }

		if(doSetAuctionTimer)
		{ setAuctionTimer(bid.AuctionId,bid.BidServerTime,serverTime); }

		if(auctionBlinks[bid.AuctionId]&&auctionBlinks[bid.AuctionId]<bid.BidId)
		{
			var jTimer=jAuction.find(".Timer");
			try
			{ jTimer.effect("highlight",{ color: "#cd0a0a" },1500); }
			catch(err)
			{ debug("updateBid effect highlight error: "+err); }
		}
		auctionBlinks[bid.AuctionId]=Math.max(bid.BidId,(auctionBlinks[bid.AuctionId]&&!isNaN(auctionBlinks[bid.AuctionId]))?auctionBlinks[bid.AuctionId]:0);

		var jAuction=auctionsDetails[bid.AuctionId];
		if(jAuction)
		{
			var savings=jAuction.AuctionCost-bid.BidPrice;
			jQuery("#Savings_"+jAuction.Id).text(formatNumber(savings,2));
			jQuery("#SavingsPercent_"+jAuction.Id).text(formatNumber(savings/jAuction.AuctionCost*100,2));
		}
	}
}

function applyBidsCounts(auctionId,bidsCounts)
{
	if(auctionId>0&&bidsCounts)
	{
		for(var i=0;i<bidsCounts.length;i++)
		{
			var rank=i+1;
			var bidCount=bidsCounts[i];

			var jElements=jQuery(".Auction_"+auctionId+" .BidsCountRank.Rank"+rank);
			jElements.find(".PublicName").text(bidCount.PublicName);
			jElements.find(".UserId").text(bidCount.UserId);
			jElements.find(".BidsCount").text(formatNumber(bidCount.Count));
			jElements.removeClass("Nobody").parents(".Nobody").removeClass("Nobody");
		}
	}
}

var setErrorDate=null;
var setErrorInterval=null;
function setError()
{
	if(isUnLoading)
	{ setSuccess(); }

	if(setErrorDate)
	{ return; }

	setErrorDate=new Date();
	setTimeout(function ()
	{
		if(!isUnLoading && setErrorDate)
		{
			var jContainer=jQuery("#ServerConnectionLost");

			var updateTimerFunction=function ()
			{
				//+1 to prevent "0s" to appear
				var duration=Math.ceil((new Date().getTime()-setErrorDate.getTime()+1)/1000);
				setTimerValue(jContainer,jContainer.find(".Timer"),null,duration,1);
			};

			setErrorInterval=setInterval(updateTimerFunction,1000);
			updateTimerFunction();

			jContainer.slideDown();
		}
	},2000);
}
function setSuccess()
{
	setErrorDate=null;
	if(setErrorInterval)
	{ clearInterval(setErrorInterval); }
	jQuery("#ServerConnectionLost").slideUp();
}

function hideMultiPrizes()
{
	if(prizesAreExclusive)
	{
		//Hide prizes when the same user is the winner of 2 prizes
		var jContainer=jQuery("#winners");
		if(jContainer.size()>0)
		{
			jContainer.find(".Prize").css("visibility","visible");
			jContainer.find(".Rank:not(.HavePrize)").find(".Prize").html("&nbsp;");
			hideMultiPrizesDuplicates(null,jContainer,".TimeRank",".BidsCountRank",1,new Array());
		}
	}
}
function hideMultiPrizesDuplicates(usersId,jContainer,selector,alternateSelector,fromRank,reportedPrizes)
{
	if(selector)
	{
		if(!usersId)
		{usersId=",";}
	
		var jRankContainer=jContainer.find(selector+".Rank"+fromRank);
		if(jRankContainer.size()>0)
		{
			var rankUserId=parseInt(jRankContainer.find(".UserId").text());

			if(rankUserId>0)
			{
				//HavePrize determines when the prize is really associated with that rank
				//If not "HavePrize" then if the prize is present that means that the prize is coming from a user that already have a prize.
				var rankHavePrize=jRankContainer.hasClass("HavePrize");

				var jPrize=jRankContainer.find(".Prize");
				var jOriginalPrize=jRankContainer.find(".OriginalPrize");

				//User already have a prize
				if(usersId.match(","+rankUserId+","))
				{
					if(rankHavePrize)
					{
						jPrize.css("visibility","hidden");
						reportedPrizes.push(jOriginalPrize.html());
					}
				}
				else if(reportedPrizes.length>0)
				{
					if(rankHavePrize)
					{ reportedPrizes.push(jOriginalPrize.html()); }

					//Take the reported prize and put it here!
					jPrize.html(reportedPrizes.shift());

					usersId+=rankUserId+",";
				}
				else
				{
					if(rankHavePrize)
					{ usersId+=rankUserId+","; }
					jPrize.html(jOriginalPrize.html());
				}
			}

			reportedPrizes=hideMultiPrizesDuplicates(usersId,jContainer,selector,null,fromRank+1,reportedPrizes);
			if(alternateSelector)
			{ reportedPrizes=hideMultiPrizesDuplicates(usersId,jContainer,alternateSelector,null,1,reportedPrizes); } //Don't report prizes accross selectors
		}
	}
	return reportedPrizes;
}


var auctionsBidsDuration=new Array();
var auctionsTimers=new Array();
var auctionsImminentTimers=new Array();
var auctionsImminentDateStart=new Array();
var loadServerTime=0;
var lastServerTime=0;	//Maintain our own serverTime, as we think is is
var updateBidTimersInterval;
function setAuctionTimer(auctionId,lastBidServerTime,serverTime)
{
	if(loadServerTime<=0)
	{loadServerTime=serverTime;}
	lastServerTime=Math.max(lastServerTime,serverTime);

	var bidServerTime=Math.max(lastBidServerTime,(bidServerTimes[auctionId] && !isNaN(bidServerTimes[auctionId]))?bidServerTimes[auctionId]:0);		//Time could also be set by the auction.DateLastBid: simply take the most recent one
	bidServerTimes[auctionId]=bidServerTime;
	
	//auctionsTimers[auctionId]=serverTime-bidServerTime;
	//Instead of saving how many time is left for each auction, save WHEN was the auction placed in our referencial
	var date=new Date();
	auctionsTimers[auctionId]=date.getTime()-(lastServerTime-bidServerTime)*1000;
	auctionsImminentTimers[auctionId]=null;
	
	updateBidTimer(auctionId,date);
	
	//debug("auctionsTimers["+auctionId+"] := "+auctionsTimers[auctionId]);
}
function setAuctionImminentTimer(auctionId,auctionDateStart,serverTime)
{
	lastServerTime=Math.max(lastServerTime,serverTime);
	auctionsImminentTimers[auctionId]=auctionDateStart-serverTime;
	auctionsImminentDateStart[auctionId]=auctionDateStart;
}
function launchUpdateBidTimers()
{
	if(updateBidTimersInterval)
	{clearInterval(updateBidTimersInterval);}
	updateBidTimersInterval=setInterval("updateBidTimers()",1000);
	updateBidTimers();
}
function updateBidTimers()
{
	var date=new Date();
	for(var auctionId in auctionsBidsDuration)
	{ updateBidTimer(auctionId,date); }
	for(var auctionId in auctionsImminentTimers)
	{ updateImminentTimer(auctionId,date); }
}
function updateBidTimer(auctionId,currentDateObj)
{
	auctionId=parseInt(auctionId);
	if(auctionId>0)
	{
		var timeLeftObject=getTimeLeftObject(auctionId,currentDateObj);
		//debug("updateBidTimer("+auctionId+") - "+timeLeftObject)
		if(timeLeftObject!=null)
		{
			var timeLeft=timeLeftObject.timeLeft;
			var bidDuration=timeLeftObject.bidDuration;

			//debug("timeLeft = "+timeLeft);
			var jAuction=jQuery("#Auction_"+auctionId);
			if(timeLeft>=0)
			{ setTimerValue(jAuction,jAuction.find(".Timer"),jQuery("#AuctionProgressBar_"+auctionId),timeLeft,bidDuration); }
		}
	}
}
function updateImminentTimer(auctionId,currentDateObj)
{
	auctionId=parseInt(auctionId);
	if(auctionId>0)
	{
		var timeLeft=--auctionsImminentTimers[auctionId];

		var jAuction=jQuery("#Auction_"+auctionId);
		if(jAuction.hasClass("Auction_status_IMMINENT")||jAuction.hasClass("Auction_DEALAUCTION"))
		{
			//jQuery("#AuctionProgressBar_"+auctionId) + auctionsImminentDateStart[auctionId]-loadServerTime is bad :(
			setTimerValue(jAuction,jAuction.find(".Timer"),null,timeLeft,1);
		}
		//else
		//{ delete auctionsImminentTimers[auctionId]; }
	}
}
function setTimerValue(jAuction,jAuctionTimer,jProgressBar,timeLeft,totalTime)
{
	timeLeft=Math.max(timeLeft,0);

	var timeLeftTmp=timeLeft;

	var days=Math.floor(timeLeftTmp/(24*60*60));
	timeLeftTmp-=days*24*60*60;
	jAuctionTimer.find(".TimerDay").text(days);
	if(days>0)
	{ jAuctionTimer.addClass("Delay_DAY"); }
	else
	{ jAuctionTimer.removeClass("Delay_DAY"); }

	var hours=Math.floor(timeLeftTmp/(60*60));
	timeLeftTmp-=hours*60*60;
	jAuctionTimer.find(".TimerHour").text(hours);
	if(hours>0)
	{ jAuctionTimer.addClass("Delay_HOUR"); }
	else
	{ jAuctionTimer.removeClass("Delay_HOUR"); }

	var minutes=Math.floor(timeLeftTmp/60);
	timeLeftTmp-=minutes*60;
	jAuctionTimer.find(".TimerMin").text((days>0 || hours>0)?padLeft(minutes,2,"0"):minutes);

	var seconds=timeLeftTmp;
	jAuctionTimer.find(".TimerSec").text(padLeft(seconds,2,"0"));

	if(timeLeft<=10)
	{ jAuction.addClass("LowTime"); }
	else
	{ jAuction.removeClass("LowTime"); }

	if(timeLeft<=2)
	{ jAuction.addClass("SuperLowTime"); }
	else
	{ jAuction.removeClass("SuperLowTime"); }

	if(jProgressBar!=null)
	{
		var percentProgress=Math.min(Math.max(100-timeLeft/Math.max(totalTime,1)*100,0),100);
		if(!isNaN(percentProgress))
		{ jProgressBar.progressbar("option","value",percentProgress); }
	}
	
	//Auction done, just wait for the push from the server
	if(timeLeft<=0)
	{ jAuction.addClass("Auction_status_CHECKING"); }
	else
	{ jAuction.removeClass("Auction_status_CHECKING"); }
}

//currentDateObj to reuse a Date object (because creating a new Date() is a lot of resources) -- this parameter is optional
function getTimeLeftObject(auctionId,currentDateObj)
{
	//var timer=incrementTimer?++auctionsTimers[auctionId]:auctionsTimers[auctionId];
	//incrementTimer is not used anymore, auctionsTimers contains WHEN the bid was placed in OUR date referencial to make sure counters are always correct, no matter when you call this function
	var auctionTimer=auctionsTimers[auctionId];
	if(auctionTimer)
	{
		//Add the roundtrip delay, min 1 second
		var timer=Math.round(((currentDateObj?currentDateObj:(new Date())).getTime()-auctionTimer)/1000)+Math.max(roundTripDelay,1);
		
		//debug("auctionsTimers["+auctionId+"] = "+timer);
		var bidDuration=auctionsBidsDuration[auctionId]-TimerMargin;
		if(bidDuration>0)
		{
			var timeLeft=bidDuration-timer;
			return { timeLeft: Math.min(Math.max(timeLeft,0),bidDuration),bidDuration: bidDuration };
		}
	}
	return null;
}


///START Auctions options menu
var auctionsDisappearTimeouts=new Array();
function appearAuctionOptions(auctionId)
{
	//debug("appearAuctionOptions");
	clearDisappearTimeout(auctionId);

	jQuery("#Auction_Options_"+auctionId).animate({ marginTop: "0" },250);
}

function disappearAuctionOptions(auctionId)
{
	//debug("disappearAuctionOptions");
	if(!auctionsDisappearTimeouts[auctionId])
	{
		//Delay the disappear to prevent the menu from appearing/disappearing/appearing/disappearing
		auctionsDisappearTimeouts[auctionId]=setTimeout(function()
		{
			jQuery("#Auction_Options_"+auctionId).animate({ marginTop: "-17px" },250);
		},50);
	}
}

function clearDisappearTimeout(auctionId)
{
	if(auctionsDisappearTimeouts[auctionId])
	{
		clearTimeout(auctionsDisappearTimeouts[auctionId]);
		auctionsDisappearTimeouts[auctionId]=null;
	}
}
///END Auctions options menu



jQuery(document).ready(function()
{
	actionDone();
	jQuery("table.alternable tbody tr:even,tr.alternable:even,ul.alternable li:even").addClass("alt");
	jQuery("#header").find(".inputText:not(.inputWithContainer),.inputButton:not(.inputWithContainer),.inputSubmit:not(.inputWithContainer),select:not(.inputWithContainer)").addClass("inputWithContainer").wrap("<div class=\"inputContainer\"></div>");
	jQuery("textarea:not(.html):not(.replyBox):not(.noAutoGrow)").addClass("noAutoGrow").autogrow({});

	/* Styled checkboxes */
	// check for what is/isn't already checked and match it on the fake ones
	jQuery("input[type='checkbox']").each(function()
	{
		var jThis=jQuery(this);
		var jFakeCheckbox=jThis.closest(".fakeInputCheckbox");
		if(jFakeCheckbox.size()>0)
		{
			jThis.addClass("displayNone");
			this.checked?jFakeCheckbox.addClass("fakeInputCheckboxOn"):jFakeCheckbox.removeClass("fakeInputCheckboxOn");
		}
	});
	// function to 'check' the fake ones and their matching checkboxes
	jQuery(".fakeInputCheckbox").click(function()
	{
		var jThis=jQuery(this);
		var checkbox=jThis.find("input[type='checkbox']").get(0);
		jThis.hasClass("fakeInputCheckboxOn")?jThis.removeClass("fakeInputCheckboxOn"):jThis.addClass("fakeInputCheckboxOn");

		if(jThis.hasClass("fakeInputCheckboxOn"))
		{ checkbox.checked=true; }
		else
		{ checkbox.checked=false; }

		return false;
	});
	/* END Styled checkboxes */

	//Define the bounce rate as people that stays less than 1 minute on the page and view only one page
	//Send an event after 1 minute to "unbounce" the page
	setTimeout("SafeTrackEvent('unbounce','unbounce','unbounce',60)",60000);

	jQuery.ajaxSetup({
		async: true,
		contentType: "application/json; charset=utf-8",
		//dataType: "json",
		dataType: "text",//Parse the JSON ourself as the JSON returned by ASP.NET webservices is malformed
		timeout: 62*2*1000,	//2 minutes timeout + 2 second margin/minute
		type: "POST",
		dataFilter: function(data,type)		//ASP.NET dates fix
		{
			//Adds double quotes around number to get valid JSON -- this works but then the dates are invalid
			//return data.replace(new RegExp(":[ \t\r\n]*([0-9\.]*)[ \t\r\n]*(\,|\})","g"),':"$1"$2');

			return parseJSON(correctAspNetJSON(data));
		},
		error: function(XMLHttpRequest,textStatus,errorThrown)
		{ debug("AJAX Network error: please check your connection.\r\nHere is the returned error: "+textStatus+" "+errorThrown); }
	});

	jQuery(window).unload(function () { isUnLoading=true; });

	setTimeout("startPush()",1000);	//Make sure auctions load rapidly, even if document is not fully loaded

	document.onclick=function(e)
	{
		actionDone()
	//	var clickContainerObj=getClickContainerObj();
	//	var topRelative=getPosition(clickContainerObj);
	//	var cursor=getCursorPosition(e);
	//	var cursorRelative={ x: cursor.x-topRelative.x,y: cursor.y-topRelative.y };
	//	logClick(cursorRelative);
	};
});

//Prevent the browser from showing "loading" state continously
window.onload=startPush;



var pushStarted=false;
var xmppPush=false;
var xmppDontReconnect=false;
var xmppPushServerIndex=-1;
var xmppConnection;
function startPush()
{
	if(!pushStarted)
	{
		pushStarted=true;

		if(pageAuctionId>0)
		{ setTimeout("getAuction("+pageAuctionId+");",1); }
		setTimeout("getEverything();",1);
		setInterval("lastServerTime++;",1000);

		startXMPPPush();
	}
}

function startXMPPPush()
{
	if(xmppDontReconnect)
	{return;}

	var jPushStatus=jQuery("#PushStatus");
	if(XMPPServer&&XMPPPushUser&&doStartPush()&&window.location.hash!="#NoXMPP")
	{
		var xmppPushServersArray=XMPPConnectServers.split(",");
		if(xmppPushServerIndex<0)
		{ xmppPushServerIndex=Math.round(Math.random()*1000); }
		else
		{ xmppPushServerIndex++; }
		xmppPushServerIndex=xmppPushServerIndex%xmppPushServersArray.length;

		//Connect as anonymous user
		var xmppChoosenServer=xmppPushServersArray[xmppPushServerIndex];
		jPushStatus.attr("title","Push server #"+xmppChoosenServer);
		//debug("/http-bind/xmpp/"+xmppChoosenServer);
		xmppConnection=new Strophe.Connection("/http-bind/xmpp/"+xmppChoosenServer);

		//xmppConnection.rawInput=function(msg) { debug(msg); };
		var extractTagValue=function(payloadText,tagName)
		{
			var regex=new RegExp("^.*<"+tagName+">(.*)</"+tagName+">.*$","g");
			return payloadText.replace(regex,"$1");
		};

		xmppConnection.addHandler(function(msg)
		{
			//"<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"+
			var msgPayloadText=jQuery(msg).text();
			//var jEntry=jQuery(msgPayloadText);	//This doesn't work in IE!!!! (well this works, but not the subsquent jEntry.find(blabla))
			var json=extractTagValue(msgPayloadText,"jsonObject");

			//debug("raw: "+msg);
			//debug("json: "+json.trim());
			//debug("json: "+correctAspNetJSON(json.trim()));
			//debug(inspect(msg));

			if(json)
			{
				json=correctAspNetJSON(json.trim());
				if(json.startsWith("{")||json.startsWith("["))
				{
					var serverTime=extractTagValue(msgPayloadText,"serverTime");
					var objectType=extractTagValue(msgPayloadText,"objectType");

					//try
					{
						var receivedObj=parseJSON(json);

						if(objectType.indexOf("BidCount")>=0&&objectType.indexOf("[]")>=0)
						{
							//TGB.BusinessLogic.Bidding.BiddingCache+BidCount[]
							//debug("pushBidCount length="+receivedObj.length);
							applyBidsCounts(pageAuctionId,receivedObj);
						}
						else if(objectType.indexOf("Auction")>=0)
						{
							//TGB.DataModel.BeterZ.DC.Auction
							//debug("pushAuction "+receivedObj.Id+" ("+receivedObj.Status+") -- "+receivedObj.DateLastBid);
							pushAuction(receivedObj,serverTime);
						}
						else if(objectType.indexOf("Bid")>=0)
						{
							//TGB.DataModel.BeterZ.DC.Bid
							//debug("pushBid "+receivedObj.BidId);
							pushBid(receivedObj,serverTime);
						}
					}
					//catch(err)
					//{ debug("Error: "+err); }
				}
			}

			return true; //Make the handler persistant!
		},null,"message","headline",null,null,null);

		//Prebinding: http://metajack.im/2009/12/14/fastest-xmpp-sessions-with-http-prebinding/
		xmppConnection.connect(XMPPServer,null,function(status)
		{
			jPushStatus.removeClass("PushConnecting").removeClass("PushDisconnected").removeClass("PushConnected");
			//debug(status);

			if(status==Strophe.Status.CONNECTING||status==Strophe.Status.AUTHENTICATING)
			{
				//debug("PushConnecting");
				jPushStatus.addClass("PushConnecting");
				xmppPush=false;
			}
			else if(status==Strophe.Status.CONNECTED||status==Strophe.Status.ATTACHED)
			{
				//debug("PushConnected");
				if(status==Strophe.Status.CONNECTED)
				{
					//function() { } to avoid this.handler is not a function
					if(startGetAuctions)
					{ xmppConnection.pubsub.subscribe(xmppConnection.jid,"pubsub."+XMPPServer,"/home/"+XMPPServer+"/"+XMPPPushUser+"/JSON/Bidding/Auctions/"+Locale,null,function() { },function() { }); }
					if(startGetBids||startGetBestBids)
					{ xmppConnection.pubsub.subscribe(xmppConnection.jid,"pubsub."+XMPPServer,"/home/"+XMPPServer+"/"+XMPPPushUser+"/JSON/Bidding/Bids",null,function() { },function() { }); }
					if(startGetBidsCounts)
					{ xmppConnection.pubsub.subscribe(xmppConnection.jid,"pubsub."+XMPPServer,"/home/"+XMPPServer+"/"+XMPPPushUser+"/JSON/Bidding/BidsCounts/AuctionId_"+pageAuctionId,null,null,null); }

					var onUnload=function()
					{
						xmppDontReconnect=true;
						xmppConnection.disconnect();
					};
					window.onunload=onUnload;
					jQuery(window).bind("unload",onUnload);

					xmppPush=true;
				}

				jPushStatus.addClass("PushConnected");
			}
			else
			{
				//debug("PushDisconnected");
				setTimeout("startXMPPPush()",2000);
				jPushStatus.addClass("PushDisconnected");
				xmppPush=false;
			}
		});

		//Allow 10 seconds to connect to the server, if it fails then connect to the next server
		setTimeout(function()
		{
			if(!xmppPush)
			{
				//Reconnection is handled by the DISCONNECTED event
				xmppConnection.disconnect();
			}
		},10000);
	}
	else
	{
		//debug("XMPP disabled");
		jPushStatus.hide();
	}
}
