var JSJAC_HAVEKEYS=true;var JSJAC_NKEYS=16;var JSJAC_INACTIVITY=300;var JSJAC_ERR_COUNT=10;var JSJAC_ALLOW_PLAIN=true;var JSJAC_CHECKQUEUEINTERVAL=100;var JSJAC_CHECKINQUEUEINTERVAL=100;var JSJACHBC_BOSH_VERSION="1.6";var JSJACHBC_USE_BOSH_VER=true;var JSJACHBC_MAX_HOLD=1;var JSJACHBC_MAX_WAIT=300;var JSJACHBC_MAXPAUSE=120;String.prototype.htmlEnc=function(){var str=this.replace(/&/g,"&amp;");str=str.replace(/</g,"&lt;");str=str.replace(/>/g,"&gt;");str=str.replace(/\"/g,"&quot;");str=str.replace(/\n/g,"<br />");return str;};Date.jab2date=function(ts){var date=new Date(Date.UTC(ts.substr(0,4),ts.substr(5,2)-1,ts.substr(8,2),ts.substr(11,2),ts.substr(14,2),ts.substr(17,2)));if(ts.substr(ts.length-6,1)!='Z'){var offset=new Date();offset.setTime(0);offset.setUTCHours(ts.substr(ts.length-5,2));offset.setUTCMinutes(ts.substr(ts.length-2,2));if(ts.substr(ts.length-6,1)=='+')
date.setTime(date.getTime()-offset.getTime());else if(ts.substr(ts.length-6,1)=='-')
date.setTime(date.getTime()+offset.getTime());}
return date;};Date.hrTime=function(ts){return Date.jab2date(ts).toLocaleString();};Date.prototype.jabberDate=function(){var padZero=function(i){if(i<10)return"0"+i;return i;};var jDate=this.getUTCFullYear()+"-";jDate+=padZero(this.getUTCMonth()+1)+"-";jDate+=padZero(this.getUTCDate())+"T";jDate+=padZero(this.getUTCHours())+":";jDate+=padZero(this.getUTCMinutes())+":";jDate+=padZero(this.getUTCSeconds())+"Z";return jDate;};Number.max=function(A,B){return(A>B)?A:B;};var hexcase=0;var b64pad="=";var chrsz=8;function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length*chrsz));}
function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length*chrsz));}
function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length*chrsz));}
function hex_hmac_sha1(key,data){return binb2hex(core_hmac_sha1(key,data));}
function b64_hmac_sha1(key,data){return binb2b64(core_hmac_sha1(key,data));}
function str_hmac_sha1(key,data){return binb2str(core_hmac_sha1(key,data));}
function sha1_vm_test()
{return hex_sha1("abc")=="a9993e364706816aba3e25717850c26c9cd0d89d";}
function core_sha1(x,len)
{x[len>>5]|=0x80<<(24-len%32);x[((len+64>>9)<<4)+15]=len;var w=Array(80);var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;var e=-1009589776;for(var i=0;i<x.length;i+=16)
{var olda=a;var oldb=b;var oldc=c;var oldd=d;var olde=e;for(var j=0;j<80;j++)
{if(j<16)w[j]=x[i+j];else w[j]=rol(w[j-3]^w[j-8]^w[j-14]^w[j-16],1);var t=safe_add(safe_add(rol(a,5),sha1_ft(j,b,c,d)),safe_add(safe_add(e,w[j]),sha1_kt(j)));e=d;d=c;c=rol(b,30);b=a;a=t;}
a=safe_add(a,olda);b=safe_add(b,oldb);c=safe_add(c,oldc);d=safe_add(d,oldd);e=safe_add(e,olde);}
return Array(a,b,c,d,e);}
function sha1_ft(t,b,c,d)
{if(t<20)return(b&c)|((~b)&d);if(t<40)return b^c^d;if(t<60)return(b&c)|(b&d)|(c&d);return b^c^d;}
function sha1_kt(t)
{return(t<20)?1518500249:(t<40)?1859775393:(t<60)?-1894007588:-899497514;}
function core_hmac_sha1(key,data)
{var bkey=str2binb(key);if(bkey.length>16)bkey=core_sha1(bkey,key.length*chrsz);var ipad=Array(16),opad=Array(16);for(var i=0;i<16;i++)
{ipad[i]=bkey[i]^0x36363636;opad[i]=bkey[i]^0x5C5C5C5C;}
var hash=core_sha1(ipad.concat(str2binb(data)),512+data.length*chrsz);return core_sha1(opad.concat(hash),512+160);}
function rol(num,cnt)
{return(num<<cnt)|(num>>>(32-cnt));}
function str2binb(str)
{var bin=Array();var mask=(1<<chrsz)-1;for(var i=0;i<str.length*chrsz;i+=chrsz)
bin[i>>5]|=(str.charCodeAt(i/chrsz)&mask)<<(32-chrsz-i%32);return bin;}
function binb2str(bin)
{var str="";var mask=(1<<chrsz)-1;for(var i=0;i<bin.length*32;i+=chrsz)
str+=String.fromCharCode((bin[i>>5]>>>(32-chrsz-i%32))&mask);return str;}
function binb2hex(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]>>((3-i%4)*8+4))&0xF)+
hex_tab.charAt((binarray[i>>2]>>((3-i%4)*8))&0xF);}
return str;}
function binb2b64(binarray)
{var tab="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var str="";for(var i=0;i<binarray.length*4;i+=3)
{var triplet=(((binarray[i>>2]>>8*(3-i%4))&0xFF)<<16)|(((binarray[i+1>>2]>>8*(3-(i+1)%4))&0xFF)<<8)|((binarray[i+2>>2]>>8*(3-(i+2)%4))&0xFF);for(var j=0;j<4;j++)
{if(i*8+j*6>binarray.length*32)str+=b64pad;else str+=tab.charAt((triplet>>6*(3-j))&0x3F);}}
return str.replace(/AAA\=(\=*?)$/,'$1');}
function hex_md5(s){return binl2hex(core_md5(str2binl(s),s.length*chrsz));}
function b64_md5(s){return binl2b64(core_md5(str2binl(s),s.length*chrsz));}
function str_md5(s){return binl2str(core_md5(str2binl(s),s.length*chrsz));}
function hex_hmac_md5(key,data){return binl2hex(core_hmac_md5(key,data));}
function b64_hmac_md5(key,data){return binl2b64(core_hmac_md5(key,data));}
function str_hmac_md5(key,data){return binl2str(core_hmac_md5(key,data));}
function md5_vm_test()
{return hex_md5("abc")=="900150983cd24fb0d6963f7d28e17f72";}
function core_md5(x,len)
{x[len>>5]|=0x80<<((len)%32);x[(((len+64)>>>9)<<4)+14]=len;var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;for(var i=0;i<x.length;i+=16)
{var olda=a;var oldb=b;var oldc=c;var 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 Array(a,b,c,d);}
function md5_cmn(q,a,b,x,s,t)
{return safe_add(bit_rol(safe_add(safe_add(a,q),safe_add(x,t)),s),b);}
function md5_ff(a,b,c,d,x,s,t)
{return md5_cmn((b&c)|((~b)&d),a,b,x,s,t);}
function md5_gg(a,b,c,d,x,s,t)
{return md5_cmn((b&d)|(c&(~d)),a,b,x,s,t);}
function md5_hh(a,b,c,d,x,s,t)
{return md5_cmn(b^c^d,a,b,x,s,t);}
function md5_ii(a,b,c,d,x,s,t)
{return md5_cmn(c^(b|(~d)),a,b,x,s,t);}
function core_hmac_md5(key,data)
{var bkey=str2binl(key);if(bkey.length>16)bkey=core_md5(bkey,key.length*chrsz);var ipad=Array(16),opad=Array(16);for(var i=0;i<16;i++)
{ipad[i]=bkey[i]^0x36363636;opad[i]=bkey[i]^0x5C5C5C5C;}
var hash=core_md5(ipad.concat(str2binl(data)),512+data.length*chrsz);return core_md5(opad.concat(hash),512+128);}
function safe_add(x,y)
{var lsw=(x&0xFFFF)+(y&0xFFFF);var msw=(x>>16)+(y>>16)+(lsw>>16);return(msw<<16)|(lsw&0xFFFF);}
function bit_rol(num,cnt)
{return(num<<cnt)|(num>>>(32-cnt));}
function str2binl(str)
{var bin=Array();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;}
function binl2str(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;}
function binl2hex(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))&0xF)+
hex_tab.charAt((binarray[i>>2]>>((i%4)*8))&0xF);}
return str;}
function binl2b64(binarray)
{var tab="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var str="";for(var i=0;i<binarray.length*4;i+=3)
{var triplet=(((binarray[i>>2]>>8*(i%4))&0xFF)<<16)|(((binarray[i+1>>2]>>8*((i+1)%4))&0xFF)<<8)|((binarray[i+2>>2]>>8*((i+2)%4))&0xFF);for(var j=0;j<4;j++)
{if(i*8+j*6>binarray.length*32)str+=b64pad;else str+=tab.charAt((triplet>>6*(3-j))&0x3F);}}
return str;}
function utf8t2d(t)
{t=t.replace(/\r\n/g,"\n");var d=new Array;var test=String.fromCharCode(237);if(test.charCodeAt(0)<0)
for(var n=0;n<t.length;n++)
{var c=t.charCodeAt(n);if(c>0)
d[d.length]=c;else{d[d.length]=(((256+c)>>6)|192);d[d.length]=(((256+c)&63)|128);}}
else
for(var n=0;n<t.length;n++)
{var c=t.charCodeAt(n);if(c<128)
d[d.length]=c;else if((c>127)&&(c<2048)){d[d.length]=((c>>6)|192);d[d.length]=((c&63)|128);}
else{d[d.length]=((c>>12)|224);d[d.length]=(((c>>6)&63)|128);d[d.length]=((c&63)|128);}}
return d;}
function utf8d2t(d)
{var r=new Array;var i=0;while(i<d.length)
{if(d[i]<128){r[r.length]=String.fromCharCode(d[i]);i++;}
else if((d[i]>191)&&(d[i]<224)){r[r.length]=String.fromCharCode(((d[i]&31)<<6)|(d[i+1]&63));i+=2;}
else{r[r.length]=String.fromCharCode(((d[i]&15)<<12)|((d[i+1]&63)<<6)|(d[i+2]&63));i+=3;}}
return r.join("");}
function b64arrays(){var b64s='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';b64=new Array();f64=new Array();for(var i=0;i<b64s.length;i++){b64[i]=b64s.charAt(i);f64[b64s.charAt(i)]=i;}}
function b64d2t(d){var r=new Array;var i=0;var dl=d.length;if((dl%3)==1){d[d.length]=0;d[d.length]=0;}
if((dl%3)==2)
d[d.length]=0;while(i<d.length)
{r[r.length]=b64[d[i]>>2];r[r.length]=b64[((d[i]&3)<<4)|(d[i+1]>>4)];r[r.length]=b64[((d[i+1]&15)<<2)|(d[i+2]>>6)];r[r.length]=b64[d[i+2]&63];i+=3;}
if((dl%3)==1)
r[r.length-1]=r[r.length-2]="=";if((dl%3)==2)
r[r.length-1]="=";var t=r.join("");return t;}
function b64t2d(t){var d=new Array;var i=0;t=t.replace(/\n|\r/g,"");t=t.replace(/=/g,"");while(i<t.length)
{d[d.length]=(f64[t.charAt(i)]<<2)|(f64[t.charAt(i+1)]>>4);d[d.length]=(((f64[t.charAt(i+1)]&15)<<4)|(f64[t.charAt(i+2)]>>2));d[d.length]=(((f64[t.charAt(i+2)]&3)<<6)|(f64[t.charAt(i+3)]));i+=4;}
if(t.length%4==2)
d=d.slice(0,d.length-2);if(t.length%4==3)
d=d.slice(0,d.length-1);return d;}
if(typeof(atob)=='undefined'||typeof(btoa)=='undefined')
b64arrays();if(typeof(atob)=='undefined'){atob=function(s){return utf8d2t(b64t2d(s));}}
if(typeof(btoa)=='undefined'){btoa=function(s){return b64d2t(utf8t2d(s));}}
function cnonce(size){var tab="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";var cnonce='';for(var i=0;i<size;i++){cnonce+=tab.charAt(Math.round(Math.random(new Date().getTime())*(tab.length-1)));}
return cnonce;}
function JSJaCJSON(){}
JSJaCJSON.toString=function(obj){var m={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},s={array:function(x){var a=['['],b,f,i,l=x.length,v;for(i=0;i<l;i+=1){v=x[i];f=s[typeof v];if(f){v=f(v);if(typeof v=='string'){if(b){a[a.length]=',';}
a[a.length]=v;b=true;}}}
a[a.length]=']';return a.join('');},'boolean':function(x){return String(x);},'null':function(x){return"null";},number:function(x){return isFinite(x)?String(x):'null';},object:function(x){if(x){if(x instanceof Array){return s.array(x);}
var a=['{'],b,f,i,v;for(i in x){if(x.hasOwnProperty(i)){v=x[i];f=s[typeof v];if(f){v=f(v);if(typeof v=='string'){if(b){a[a.length]=',';}
a.push(s.string(i),':',v);b=true;}}}}
a[a.length]='}';return a.join('');}
return'null';},string:function(x){if(/["\\\x00-\x1f]/.test(x)){x=x.replace(/([\x00-\x1f\\"])/g,function(a,b){var c=m[b];if(c){return c;}
c=b.charCodeAt();return'\\u00'+
Math.floor(c/16).toString(16)+
(c%16).toString(16);});}
return'"'+x+'"';}};switch(typeof(obj)){case'object':return s.object(obj);case'array':return s.array(obj);}};JSJaCJSON.parse=function(str){try{return!(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(str.replace(/"(\\.|[^"\\])*"/g,'')))&&eval('('+str+')');}catch(e){return false;}};function XmlHttp(){}
XmlHttp.create=function(){try{if(window.XMLHttpRequest){var req=new XMLHttpRequest();if(req.readyState==null){req.readyState=1;req.addEventListener("load",function(){req.readyState=4;if(typeof req.onreadystatechange=="function")
req.onreadystatechange();},false);}
return req;}
if(window.ActiveXObject){return new ActiveXObject(XmlHttp.getPrefix()+".XmlHttp");}}
catch(ex){}
throw new Error("Your browser does not support XmlHttp objects");};XmlHttp.getPrefix=function(){if(XmlHttp.prefix)
return XmlHttp.prefix;var prefixes=["MSXML2","Microsoft","MSXML","MSXML3"];var o;for(var i=0;i<prefixes.length;i++){try{o=new ActiveXObject(prefixes[i]+".XmlHttp");return XmlHttp.prefix=prefixes[i];}
catch(ex){};}
throw new Error("Could not find an installed XML parser");};function XmlDocument(){}
XmlDocument.create=function(name,ns){name=name||'foo';ns=ns||'';try{var doc;if(document.implementation&&document.implementation.createDocument){doc=document.implementation.createDocument(ns,name,null);if(doc.readyState==null){doc.readyState=1;doc.addEventListener("load",function(){doc.readyState=4;if(typeof doc.onreadystatechange=="function")
doc.onreadystatechange();},false);}}else if(window.ActiveXObject){doc=new ActiveXObject(XmlDocument.getPrefix()+".DomDocument");}
if(!doc.documentElement||doc.documentElement.tagName!=name||(doc.documentElement.namespaceURI&&doc.documentElement.namespaceURI!=ns)){try{if(ns!='')
doc.appendChild(doc.createElement(name)).setAttribute('xmlns',ns);else
doc.appendChild(doc.createElement(name));}catch(dex){doc=document.implementation.createDocument(ns,name,null);if(doc.documentElement==null)
doc.appendChild(doc.createElement(name));if(ns!=''&&doc.documentElement.getAttribute('xmlns')!=ns){doc.documentElement.setAttribute('xmlns',ns);}}}
return doc;}
catch(ex){alert(ex.name+": "+ex.message);}
throw new Error("Your browser does not support XmlDocument objects");};XmlDocument.getPrefix=function(){if(XmlDocument.prefix)
return XmlDocument.prefix;var prefixes=["MSXML2","Microsoft","MSXML","MSXML3"];var o;for(var i=0;i<prefixes.length;i++){try{o=new ActiveXObject(prefixes[i]+".DomDocument");return XmlDocument.prefix=prefixes[i];}
catch(ex){};}
throw new Error("Could not find an installed XML parser");};if(typeof(Document)!='undefined'&&window.DOMParser){Document.prototype.loadXML=function(s){var doc2=(new DOMParser()).parseFromString(s,"text/xml");while(this.hasChildNodes())
this.removeChild(this.lastChild);for(var i=0;i<doc2.childNodes.length;i++){this.appendChild(this.importNode(doc2.childNodes[i],true));}};}
if(window.XMLSerializer&&window.Node&&Node.prototype&&Node.prototype.__defineGetter__){XMLDocument.prototype.__defineGetter__("xml",function(){return(new XMLSerializer()).serializeToString(this);});Document.prototype.__defineGetter__("xml",function(){return(new XMLSerializer()).serializeToString(this);});Node.prototype.__defineGetter__("xml",function(){return(new XMLSerializer()).serializeToString(this);});}
var JSJaCBuilder={buildNode:function(doc,elementName){var element,ns=arguments[4];if(arguments[2])
if(JSJaCBuilder._isStringOrNumber(arguments[2])||(arguments[2]instanceof Array)){element=this._createElement(doc,elementName,ns);JSJaCBuilder._children(doc,element,arguments[2]);}else{ns=arguments[2]['xmlns']||ns;element=this._createElement(doc,elementName,ns);for(attr in arguments[2]){if(arguments[2].hasOwnProperty(attr)&&attr!='xmlns')
element.setAttribute(attr,arguments[2][attr]);}}
else
element=this._createElement(doc,elementName,ns);if(arguments[3])
JSJaCBuilder._children(doc,element,arguments[3],ns);return element;},_createElement:function(doc,elementName,ns){try{if(ns)
return doc.createElementNS(ns,elementName);}catch(ex){}
var el=doc.createElement(elementName);if(ns)
el.setAttribute("xmlns",ns);return el;},_text:function(doc,text){return doc.createTextNode(text);},_children:function(doc,element,children,ns){if(typeof children=='object'){for(var i in children){if(children.hasOwnProperty(i)){var e=children[i];if(typeof e=='object'){if(e instanceof Array){var node=JSJaCBuilder.buildNode(doc,e[0],e[1],e[2],ns);element.appendChild(node);}else{element.appendChild(e);}}else{if(JSJaCBuilder._isStringOrNumber(e)){element.appendChild(JSJaCBuilder._text(doc,e));}}}}}else{if(JSJaCBuilder._isStringOrNumber(children)){element.appendChild(JSJaCBuilder._text(doc,children));}}},_attributes:function(attributes){var attrs=[];for(attribute in attributes)
if(attributes.hasOwnProperty(attribute))
attrs.push(attribute+'="'+attributes[attribute].toString().htmlEnc()+'"');return attrs.join(" ");},_isStringOrNumber:function(param){return(typeof param=='string'||typeof param=='number');}};var NS_DISCO_ITEMS="http://jabber.org/protocol/disco#items";var NS_DISCO_INFO="http://jabber.org/protocol/disco#info";var NS_VCARD="vcard-temp";var NS_AUTH="jabber:iq:auth";var NS_AUTH_ERROR="jabber:iq:auth:error";var NS_REGISTER="jabber:iq:register";var NS_SEARCH="jabber:iq:search";var NS_ROSTER="jabber:iq:roster";var NS_PRIVACY="jabber:iq:privacy";var NS_PRIVATE="jabber:iq:private";var NS_VERSION="jabber:iq:version";var NS_TIME="jabber:iq:time";var NS_LAST="jabber:iq:last";var NS_XDATA="jabber:x:data";var NS_IQDATA="jabber:iq:data";var NS_DELAY="jabber:x:delay";var NS_EXPIRE="jabber:x:expire";var NS_EVENT="jabber:x:event";var NS_XCONFERENCE="jabber:x:conference";var NS_STATS="http://jabber.org/protocol/stats";var NS_MUC="http://jabber.org/protocol/muc";var NS_MUC_USER="http://jabber.org/protocol/muc#user";var NS_MUC_ADMIN="http://jabber.org/protocol/muc#admin";var NS_MUC_OWNER="http://jabber.org/protocol/muc#owner";var NS_PUBSUB="http://jabber.org/protocol/pubsub";var NS_PUBSUB_EVENT="http://jabber.org/protocol/pubsub#event";var NS_PUBSUB_OWNER="http://jabber.org/protocol/pubsub#owner";var NS_PUBSUB_NMI="http://jabber.org/protocol/pubsub#node-meta-info";var NS_COMMANDS="http://jabber.org/protocol/commands";var NS_STREAM="http://etherx.jabber.org/streams";var NS_STANZAS="urn:ietf:params:xml:ns:xmpp-stanzas";var NS_STREAMS="urn:ietf:params:xml:ns:xmpp-streams";var NS_TLS="urn:ietf:params:xml:ns:xmpp-tls";var NS_SASL="urn:ietf:params:xml:ns:xmpp-sasl";var NS_SESSION="urn:ietf:params:xml:ns:xmpp-session";var NS_BIND="urn:ietf:params:xml:ns:xmpp-bind";var NS_FEATURE_IQAUTH="http://jabber.org/features/iq-auth";var NS_FEATURE_IQREGISTER="http://jabber.org/features/iq-register";var NS_FEATURE_COMPRESS="http://jabber.org/features/compress";var NS_COMPRESS="http://jabber.org/protocol/compress";function STANZA_ERROR(code,type,cond){if(window==this)
return new STANZA_ERROR(code,type,cond);this.code=code;this.type=type;this.cond=cond;}
var ERR_BAD_REQUEST=STANZA_ERROR("400","modify","bad-request");var ERR_CONFLICT=STANZA_ERROR("409","cancel","conflict");var ERR_FEATURE_NOT_IMPLEMENTED=STANZA_ERROR("501","cancel","feature-not-implemented");var ERR_FORBIDDEN=STANZA_ERROR("403","auth","forbidden");var ERR_GONE=STANZA_ERROR("302","modify","gone");var ERR_INTERNAL_SERVER_ERROR=STANZA_ERROR("500","wait","internal-server-error");var ERR_ITEM_NOT_FOUND=STANZA_ERROR("404","cancel","item-not-found");var ERR_JID_MALFORMED=STANZA_ERROR("400","modify","jid-malformed");var ERR_NOT_ACCEPTABLE=STANZA_ERROR("406","modify","not-acceptable");var ERR_NOT_ALLOWED=STANZA_ERROR("405","cancel","not-allowed");var ERR_NOT_AUTHORIZED=STANZA_ERROR("401","auth","not-authorized");var ERR_PAYMENT_REQUIRED=STANZA_ERROR("402","auth","payment-required");var ERR_RECIPIENT_UNAVAILABLE=STANZA_ERROR("404","wait","recipient-unavailable");var ERR_REDIRECT=STANZA_ERROR("302","modify","redirect");var ERR_REGISTRATION_REQUIRED=STANZA_ERROR("407","auth","registration-required");var ERR_REMOTE_SERVER_NOT_FOUND=STANZA_ERROR("404","cancel","remote-server-not-found");var ERR_REMOTE_SERVER_TIMEOUT=STANZA_ERROR("504","wait","remote-server-timeout");var ERR_RESOURCE_CONSTRAINT=STANZA_ERROR("500","wait","resource-constraint");var ERR_SERVICE_UNAVAILABLE=STANZA_ERROR("503","cancel","service-unavailable");var ERR_SUBSCRIPTION_REQUIRED=STANZA_ERROR("407","auth","subscription-required");var ERR_UNEXPECTED_REQUEST=STANZA_ERROR("400","wait","unexpected-request");function JSJaCConsoleLogger(level){this.level=level||4;this.start=function(){};this.log=function(msg,level){level=level||0;if(level>this.level)
return;if(typeof(console)=='undefined')
return;try{switch(level){case 0:console.warn(msg);break;case 1:console.error(msg);break;case 2:console.info(msg);break;case 4:console.debug(msg);break;default:console.log(msg);break;}}catch(e){try{console.log(msg)}catch(e){}}};this.setLevel=function(level){this.level=level;return this;};this.getLevel=function(){return this.level;};}
function JSJaCCookie(name,value,secs)
{if(window==this)
return new JSJaCCookie(name,value,secs);this.name=name;this.value=value;this.secs=secs;this.write=function(){if(this.secs){var date=new Date();date.setTime(date.getTime()+(this.secs*1000));var expires="; expires="+date.toGMTString();}else
var expires="";document.cookie=this.getName()+"="+this.getValue()+expires+"; path=/";};this.erase=function(){var c=new JSJaCCookie(this.getName(),"",-1);c.write();};this.getName=function(){return this.name;};this.setName=function(name){this.name=name;return this;};this.getValue=function(){return this.value;};this.setValue=function(value){this.value=value;return this;};}
JSJaCCookie.read=function(name){var nameEQ=name+"=";var ca=document.cookie.split(';');for(var i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)==' ')c=c.substring(1,c.length);if(c.indexOf(nameEQ)==0)return new JSJaCCookie(name,c.substring(nameEQ.length,c.length));}
throw new JSJaCCookieException("Cookie not found");};JSJaCCookie.get=function(name){return JSJaCCookie.read(name).getValue();};JSJaCCookie.remove=function(name){JSJaCCookie.read(name).erase();};function JSJaCCookieException(msg){this.message=msg;this.name="CookieException";}
function JSJaCError(code,type,condition){var xmldoc=XmlDocument.create("error","jsjac");condition=condition||'undefined';xmldoc.documentElement.setAttribute('code',code);xmldoc.documentElement.setAttribute('type',type);xmldoc.documentElement.appendChild(xmldoc.createElement(condition)).setAttribute('xmlns','urn:ietf:params:xml:ns:xmpp-stanzas');return xmldoc.documentElement;}
var JSJACJID_FORBIDDEN=['"',' ','&','\'','/',':','<','>','@'];function JSJaCJID(jid){this._node='';this._domain='';this._resource='';if(typeof(jid)=='string'){if(jid.indexOf('@')!=-1){this.setNode(jid.substring(0,jid.indexOf('@')));jid=jid.substring(jid.indexOf('@')+1);}
if(jid.indexOf('/')!=-1){this.setResource(jid.substring(jid.indexOf('/')+1));jid=jid.substring(0,jid.indexOf('/'));}
this.setDomain(jid);}else{this.setNode(jid.node);this.setDomain(jid.domain);this.setResource(jid.resource);}}
JSJaCJID.prototype.getNode=function(){return this._node;};JSJaCJID.prototype.getDomain=function(){return this._domain;};JSJaCJID.prototype.getResource=function(){return this._resource;};JSJaCJID.prototype.setNode=function(node){JSJaCJID._checkNodeName(node);this._node=node||'';return this;};JSJaCJID.prototype.setDomain=function(domain){if(!domain||domain=='')
throw new JSJaCJIDInvalidException("domain name missing");JSJaCJID._checkNodeName(domain);this._domain=domain;return this;};JSJaCJID.prototype.setResource=function(resource){this._resource=resource||'';return this;};JSJaCJID.prototype.toString=function(){var jid='';if(this.getNode()&&this.getNode()!='')
jid=this.getNode()+'@';jid+=this.getDomain();if(this.getResource()&&this.getResource()!="")
jid+='/'+this.getResource();return jid;};JSJaCJID.prototype.removeResource=function(){return this.setResource();};JSJaCJID.prototype.clone=function(){return new JSJaCJID(this.toString());};JSJaCJID.prototype.isEntity=function(jid){if(typeof jid=='string')
jid=(new JSJaCJID(jid));jid.removeResource();return(this.clone().removeResource().toString()===jid.toString());};JSJaCJID._checkNodeName=function(nodeprep){if(!nodeprep||nodeprep=='')
return;for(var i=0;i<JSJACJID_FORBIDDEN.length;i++){if(nodeprep.indexOf(JSJACJID_FORBIDDEN[i])!=-1){throw new JSJaCJIDInvalidException("forbidden char in nodename: "+JSJACJID_FORBIDDEN[i]);}}};function JSJaCJIDInvalidException(message){this.message=message;this.name="JSJaCJIDInvalidException";}
function JSJaCKeys(func,oDbg){var seed=Math.random();this._k=new Array();this._k[0]=seed.toString();if(oDbg)
this.oDbg=oDbg;else{this.oDbg={};this.oDbg.log=function(){};}
if(func){for(var i=1;i<JSJAC_NKEYS;i++){this._k[i]=func(this._k[i-1]);oDbg.log(i+": "+this._k[i],4);}}
this._indexAt=JSJAC_NKEYS-1;this.getKey=function(){return this._k[this._indexAt--];};this.lastKey=function(){return(this._indexAt==0);};this.size=function(){return this._k.length;};this._getSuspendVars=function(){return('_k,_indexAt').split(',');}}
var JSJACPACKET_USE_XMLNS=true;function JSJaCPacket(name){this.name=name;if(typeof(JSJACPACKET_USE_XMLNS)!='undefined'&&JSJACPACKET_USE_XMLNS)
this.doc=XmlDocument.create(name,'jabber:client');else
this.doc=XmlDocument.create(name,'');}
JSJaCPacket.prototype.pType=function(){return this.name;};JSJaCPacket.prototype.getDoc=function(){return this.doc;};JSJaCPacket.prototype.getNode=function(){if(this.getDoc()&&this.getDoc().documentElement)
return this.getDoc().documentElement;else
return null;};JSJaCPacket.prototype.setTo=function(to){if(!to||to=='')
this.getNode().removeAttribute('to');else if(typeof(to)=='string')
this.getNode().setAttribute('to',to);else
this.getNode().setAttribute('to',to.toString());return this;};JSJaCPacket.prototype.setFrom=function(from){if(!from||from=='')
this.getNode().removeAttribute('from');else if(typeof(from)=='string')
this.getNode().setAttribute('from',from);else
this.getNode().setAttribute('from',from.toString());return this;};JSJaCPacket.prototype.setID=function(id){if(!id||id=='')
this.getNode().removeAttribute('id');else
this.getNode().setAttribute('id',id);return this;};JSJaCPacket.prototype.setType=function(type){if(!type||type=='')
this.getNode().removeAttribute('type');else
this.getNode().setAttribute('type',type);return this;};JSJaCPacket.prototype.setXMLLang=function(xmllang){if(!xmllang||xmllang=='')
this.getNode().removeAttribute('xml:lang');else
this.getNode().setAttribute('xml:lang',xmllang);return this;};JSJaCPacket.prototype.getTo=function(){return this.getNode().getAttribute('to');};JSJaCPacket.prototype.getFrom=function(){return this.getNode().getAttribute('from');};JSJaCPacket.prototype.getToJID=function(){return new JSJaCJID(this.getTo());};JSJaCPacket.prototype.getFromJID=function(){return new JSJaCJID(this.getFrom());};JSJaCPacket.prototype.getID=function(){return this.getNode().getAttribute('id');};JSJaCPacket.prototype.getType=function(){return this.getNode().getAttribute('type');};JSJaCPacket.prototype.getXMLLang=function(){return this.getNode().getAttribute('xml:lang');};JSJaCPacket.prototype.getXMLNS=function(){return this.getNode().namespaceURI;};JSJaCPacket.prototype.getChild=function(name,ns){if(!this.getNode()){return null;}
name=name||'*';ns=ns||'*';if(this.getNode().getElementsByTagNameNS){return this.getNode().getElementsByTagNameNS(ns,name).item(0);}
var nodes=this.getNode().getElementsByTagName(name);if(ns!='*'){for(var i=0;i<nodes.length;i++){if(nodes.item(i).namespaceURI==ns){return nodes.item(i);}}}else{return nodes.item(0);}
return null;}
JSJaCPacket.prototype.getChildVal=function(name,ns){var node=this.getChild(name,ns);var ret='';if(node&&node.hasChildNodes()){for(var i=0;i<node.childNodes.length;i++)
if(node.childNodes.item(i).nodeValue)
ret+=node.childNodes.item(i).nodeValue;}
return ret;};JSJaCPacket.prototype.clone=function(){return JSJaCPacket.wrapNode(this.getNode());};JSJaCPacket.prototype.isError=function(){return(this.getType()=='error');};JSJaCPacket.prototype.errorReply=function(stanza_error){var rPacket=this.clone();rPacket.setTo(this.getFrom());rPacket.setFrom();rPacket.setType('error');rPacket.appendNode('error',{code:stanza_error.code,type:stanza_error.type},[[stanza_error.cond]]);return rPacket;};JSJaCPacket.prototype.xml=typeof XMLSerializer!='undefined'?function(){var r=(new XMLSerializer()).serializeToString(this.getNode());if(typeof(r)=='undefined')
r=(new XMLSerializer()).serializeToString(this.doc);return r}:function(){return this.getDoc().xml};JSJaCPacket.prototype._getAttribute=function(attr){return this.getNode().getAttribute(attr);};JSJaCPacket.prototype._replaceNode=function(aNode){for(var i=0;i<aNode.attributes.length;i++)
if(aNode.attributes.item(i).nodeName!='xmlns')
this.getNode().setAttribute(aNode.attributes.item(i).nodeName,aNode.attributes.item(i).nodeValue);for(var i=0;i<aNode.childNodes.length;i++)
if(this.getDoc().importNode)
this.getNode().appendChild(this.getDoc().importNode(aNode.childNodes.item(i),true));else
this.getNode().appendChild(aNode.childNodes.item(i).cloneNode(true));};JSJaCPacket.prototype._setChildNode=function(nodeName,nodeValue){var aNode=this.getChild(nodeName);var tNode=this.getDoc().createTextNode(nodeValue);if(aNode)
try{aNode.replaceChild(tNode,aNode.firstChild);}catch(e){}
else{try{aNode=this.getDoc().createElementNS(this.getNode().namespaceURI,nodeName);}catch(ex){aNode=this.getDoc().createElement(nodeName)}
this.getNode().appendChild(aNode);aNode.appendChild(tNode);}
return aNode;};JSJaCPacket.prototype.buildNode=function(elementName){return JSJaCBuilder.buildNode(this.getDoc(),elementName,arguments[1],arguments[2]);};JSJaCPacket.prototype.appendNode=function(element){if(typeof element=='object'){return this.getNode().appendChild(element)}else{return this.getNode().appendChild(this.buildNode(element,arguments[1],arguments[2],null,this.getNode().namespaceURI));}};function JSJaCPresence(){this.base=JSJaCPacket;this.base('presence');}
JSJaCPresence.prototype=new JSJaCPacket;JSJaCPresence.prototype.setStatus=function(status){this._setChildNode("status",status);return this;};JSJaCPresence.prototype.setShow=function(show){if(show=='chat'||show=='away'||show=='xa'||show=='dnd')
this._setChildNode("show",show);return this;};JSJaCPresence.prototype.setPriority=function(prio){this._setChildNode("priority",prio);return this;};JSJaCPresence.prototype.setPresence=function(show,status,prio){if(show)
this.setShow(show);if(status)
this.setStatus(status);if(prio)
this.setPriority(prio);return this;};JSJaCPresence.prototype.getStatus=function(){return this.getChildVal('status');};JSJaCPresence.prototype.getShow=function(){return this.getChildVal('show');};JSJaCPresence.prototype.getPriority=function(){return this.getChildVal('priority');};function JSJaCIQ(){this.base=JSJaCPacket;this.base('iq');}
JSJaCIQ.prototype=new JSJaCPacket;JSJaCIQ.prototype.setIQ=function(to,type,id){if(to)
this.setTo(to);if(type)
this.setType(type);if(id)
this.setID(id);return this;};JSJaCIQ.prototype.setQuery=function(xmlns){var query;try{query=this.getDoc().createElementNS(xmlns,'query');}catch(e){query=this.getDoc().createElement('query');}
if(query&&query.getAttribute('xmlns')!=xmlns)
query.setAttribute('xmlns',xmlns);this.getNode().appendChild(query);return query;};JSJaCIQ.prototype.getQuery=function(){return this.getNode().getElementsByTagName('query').item(0);};JSJaCIQ.prototype.getQueryXMLNS=function(){if(this.getQuery())
return this.getQuery().namespaceURI;else
return null;};JSJaCIQ.prototype.reply=function(payload){var rIQ=this.clone();rIQ.setTo(this.getFrom());rIQ.setType('result');if(payload){if(typeof payload=='string')
rIQ.getChild().appendChild(rIQ.getDoc().loadXML(payload));else if(payload.constructor==Array){var node=rIQ.getChild();for(var i=0;i<payload.length;i++)
if(typeof payload[i]=='string')
node.appendChild(rIQ.getDoc().loadXML(payload[i]));else if(typeof payload[i]=='object')
node.appendChild(payload[i]);}
else if(typeof payload=='object')
rIQ.getChild().appendChild(payload);}
return rIQ;};function JSJaCMessage(){this.base=JSJaCPacket;this.base('message');}
JSJaCMessage.prototype=new JSJaCPacket;JSJaCMessage.prototype.setBody=function(body){this._setChildNode("body",body);return this;};JSJaCMessage.prototype.setSubject=function(subject){this._setChildNode("subject",subject);return this;};JSJaCMessage.prototype.setThread=function(thread){this._setChildNode("thread",thread);return this;};JSJaCMessage.prototype.getThread=function(){return this.getChildVal('thread');};JSJaCMessage.prototype.getBody=function(){return this.getChildVal('body');};JSJaCMessage.prototype.getSubject=function(){return this.getChildVal('subject')};JSJaCPacket.wrapNode=function(node){try{var aNode;switch(node.nodeName.toLowerCase()){case'presence':aNode=new JSJaCPresence();break;case'message':aNode=new JSJaCMessage();break;case'iq':aNode=new JSJaCIQ();break;default:return null;}
aNode._replaceNode(node);return aNode;}catch(ex){return null;}};function JSJaCConnection(oArg){if(oArg&&oArg.oDbg&&oArg.oDbg.log)
this.oDbg=oArg.oDbg;else{this.oDbg=new Object();this.oDbg.log=function(){};}
if(oArg&&oArg.httpbase)
this._httpbase=oArg.httpbase;if(oArg&&oArg.allow_plain)
this.allow_plain=oArg.allow_plain;else
this.allow_plain=JSJAC_ALLOW_PLAIN;this._connected=false;this._events=new Array();this._keys=null;this._ID=0;this._inQ=new Array();this._pQueue=new Array();this._regIDs=new Array();this._req=new Array();this._status='intialized';this._errcnt=0;this._inactivity=JSJAC_INACTIVITY;this._sendRawCallbacks=new Array();if(oArg&&oArg.timerval)
this.setPollInterval(oArg.timerval);}
JSJaCConnection.prototype.connect=function(oArg){this._setStatus('connecting');this.domain=oArg.domain||'localhost';this.username=oArg.username;this.resource=oArg.resource;this.pass=oArg.pass;this.register=oArg.register;this.authhost=oArg.authhost||this.domain;this.authtype=oArg.authtype||'sasl';if(oArg.xmllang&&oArg.xmllang!='')
this._xmllang=oArg.xmllang;this.host=oArg.host||this.domain;this.port=oArg.port||5222;if(oArg.secure)
this.secure='true';else
this.secure='false';if(oArg.wait)
this._wait=oArg.wait;this.jid=this.username+'@'+this.domain;this.fulljid=this.jid+'/'+this.resource;this._rid=Math.round(100000.5+(((900000.49999)-(100000.5))*Math.random()));var slot=this._getFreeSlot();this._req[slot]=this._setupRequest(true);var reqstr=this._getInitialRequestString();this.oDbg.log(reqstr,4);this._req[slot].r.onreadystatechange=JSJaC.bind(function(){if(this._req[slot].r.readyState==4){this.oDbg.log("async recv: "+this._req[slot].r.responseText,4);this._handleInitialResponse(slot);}},this);if(typeof(this._req[slot].r.onerror)!='undefined'){this._req[slot].r.onerror=JSJaC.bind(function(e){this.oDbg.log('XmlHttpRequest error',1);return false;},this);}
this._req[slot].r.send(reqstr);};JSJaCConnection.prototype.connected=function(){return this._connected;};JSJaCConnection.prototype.disconnect=function(){this._setStatus('disconnecting');if(!this.connected())
return;this._connected=false;clearInterval(this._interval);clearInterval(this._inQto);if(this._timeout)
clearTimeout(this._timeout);var slot=this._getFreeSlot();this._req[slot]=this._setupRequest(false);request=this._getRequestString(false,true);this.oDbg.log("Disconnecting: "+request,4);this._req[slot].r.send(request);try{JSJaCCookie.read('JSJaC_State').erase();}catch(e){}
this.oDbg.log("Disconnected: "+this._req[slot].r.responseText,2);this._handleEvent('ondisconnect');};JSJaCConnection.prototype.getPollInterval=function(){return this._timerval;};JSJaCConnection.prototype.registerHandler=function(event){event=event.toLowerCase();var eArg={handler:arguments[arguments.length-1],childName:'*',childNS:'*',type:'*'};if(arguments.length>2)
eArg.childName=arguments[1];if(arguments.length>3)
eArg.childNS=arguments[2];if(arguments.length>4)
eArg.type=arguments[3];if(!this._events[event])
this._events[event]=new Array(eArg);else
this._events[event]=this._events[event].concat(eArg);this._events[event]=this._events[event].sort(function(a,b){var aRank=0;var bRank=0;with(a){if(type=='*')
aRank++;if(childNS=='*')
aRank++;if(childName=='*')
aRank++;}
with(b){if(type=='*')
bRank++;if(childNS=='*')
bRank++;if(childName=='*')
bRank++;}
if(aRank>bRank)
return 1;if(aRank<bRank)
return-1;return 0;});this.oDbg.log("registered handler for event '"+event+"'",2);};JSJaCConnection.prototype.unregisterHandler=function(event,handler){event=event.toLowerCase();if(!this._events[event])
return;var arr=this._events[event],res=new Array();for(var i=0;i<arr.length;i++)
if(arr[i].handler!=handler)
res.push(arr[i]);if(arr.length!=res.length){this._events[event]=res;this.oDbg.log("unregistered handler for event '"+event+"'",2);}};JSJaCConnection.prototype.registerIQGet=function(childName,childNS,handler){this.registerHandler('iq',childName,childNS,'get',handler);};JSJaCConnection.prototype.registerIQSet=function(childName,childNS,handler){this.registerHandler('iq',childName,childNS,'set',handler);};JSJaCConnection.prototype.resume=function(){try{this._setStatus('resuming');var s=unescape(JSJaCCookie.read('JSJaC_State').getValue());this.oDbg.log('read cookie: '+s,2);var o=JSJaCJSON.parse(s);for(var i in o)
if(o.hasOwnProperty(i))
this[i]=o[i];if(this._keys){this._keys2=new JSJaCKeys();var u=this._keys2._getSuspendVars();for(var i=0;i<u.length;i++)
this._keys2[u[i]]=this._keys[u[i]];this._keys=this._keys2;}
try{JSJaCCookie.read('JSJaC_State').erase();}catch(e){}
if(this._connected){this._handleEvent('onresume');setTimeout(JSJaC.bind(this._resume,this),this.getPollInterval());this._interval=setInterval(JSJaC.bind(this._checkQueue,this),JSJAC_CHECKQUEUEINTERVAL);this._inQto=setInterval(JSJaC.bind(this._checkInQ,this),JSJAC_CHECKINQUEUEINTERVAL);}
return(this._connected===true);}catch(e){if(e.message)
this.oDbg.log("Resume failed: "+e.message,1);else
this.oDbg.log("Resume failed: "+e,1);return false;}};JSJaCConnection.prototype.send=function(packet,cb,arg){if(!packet||!packet.pType){this.oDbg.log("no packet: "+packet,1);return false;}
if(!this.connected())
return false;if(cb){if(!packet.getID())
packet.setID('JSJaCID_'+this._ID++);this._registerPID(packet.getID(),cb,arg);}
try{this._handleEvent(packet.pType()+'_out',packet);this._handleEvent("packet_out",packet);this._pQueue=this._pQueue.concat(packet.xml());}catch(e){this.oDbg.log(e.toString(),1);return false;}
return true;};JSJaCConnection.prototype.sendIQ=function(iq,handlers,arg){if(!iq||iq.pType()!='iq'){return false;}
handlers=handlers||{};var error_handler=handlers.error_handler||function(aIq){this.oDbg.log(iq.xml(),1);};var result_handler=handlers.result_handler||function(aIq){this.oDbg.log(aIq.xml(),2);};var default_handler=handlers.default_handler||function(aIq){this.oDbg.log(aIq.xml(),2);};var iqHandler=function(aIq,arg){switch(aIq.getType()){case'error':error_handler(aIq);break;case'result':result_handler(aIq,arg);break;default:default_handler(aIq,arg);}};return this.send(iq,iqHandler,arg);};JSJaCConnection.prototype.setPollInterval=function(timerval){if(timerval&&!isNaN(timerval))
this._timerval=timerval;return this._timerval;};JSJaCConnection.prototype.status=function(){return this._status;};JSJaCConnection.prototype.suspend=function(){clearTimeout(this._timeout);clearInterval(this._interval);clearInterval(this._inQto);this._suspend();var u=('_connected,_keys,_ID,_inQ,_pQueue,_regIDs,_errcnt,_inactivity,domain,username,resource,jid,fulljid,_sid,_httpbase,_timerval,_is_polling').split(',');u=u.concat(this._getSuspendVars());var s=new Object();for(var i=0;i<u.length;i++){if(!this[u[i]])continue;if(this[u[i]]._getSuspendVars){var uo=this[u[i]]._getSuspendVars();var o=new Object();for(var j=0;j<uo.length;j++)
o[uo[j]]=this[u[i]][uo[j]];}else
var o=this[u[i]];s[u[i]]=o;}
var c=new JSJaCCookie('JSJaC_State',escape(JSJaCJSON.toString(s)),this._inactivity);this.oDbg.log("writing cookie: "+unescape(c.value)+"\n(length:"+
unescape(c.value).length+")",2);c.write();try{var c2=JSJaCCookie.read('JSJaC_State');if(c.value!=c2.value){this.oDbg.log("Suspend failed writing cookie.\nRead: "+
unescape(JSJaCCookie.read('JSJaC_State')),1);c.erase();}
this._connected=false;this._setStatus('suspending');}catch(e){this.oDbg.log("Failed reading cookie 'JSJaC_State': "+e.message);}};JSJaCConnection.prototype._abort=function(){clearTimeout(this._timeout);clearInterval(this._inQto);clearInterval(this._interval);this._connected=false;this._setStatus('aborted');this.oDbg.log("Disconnected.",1);this._handleEvent('ondisconnect');this._handleEvent('onerror',JSJaCError('500','cancel','service-unavailable'));};JSJaCConnection.prototype._checkInQ=function(){for(var i=0;i<this._inQ.length&&i<10;i++){var item=this._inQ[0];this._inQ=this._inQ.slice(1,this._inQ.length);var packet=JSJaCPacket.wrapNode(item);if(!packet)
return;this._handleEvent("packet_in",packet);if(packet.pType&&!this._handlePID(packet)){this._handleEvent(packet.pType()+'_in',packet);this._handleEvent(packet.pType(),packet);}}};JSJaCConnection.prototype._checkQueue=function(){if(this._pQueue.length!=0)
this._process();return true;};JSJaCConnection.prototype._doAuth=function(){if(this.has_sasl&&this.authtype=='nonsasl')
this.oDbg.log("Warning: SASL present but not used",1);if(!this._doSASLAuth()&&!this._doLegacyAuth()){this.oDbg.log("Auth failed for authtype "+this.authtype,1);this.disconnect();return false;}
return true;};JSJaCConnection.prototype._doInBandReg=function(){if(this.authtype=='saslanon'||this.authtype=='anonymous')
return;var iq=new JSJaCIQ();iq.setType('set');iq.setID('reg1');iq.appendNode("query",{xmlns:"jabber:iq:register"},[["username",this.username],["password",this.pass]]);this.send(iq,this._doInBandRegDone);};JSJaCConnection.prototype._doInBandRegDone=function(iq){if(iq&&iq.getType()=='error'){this.oDbg.log("registration failed for "+this.username,0);this._handleEvent('onerror',iq.getChild('error'));return;}
this.oDbg.log(this.username+" registered succesfully",0);this._doAuth();};JSJaCConnection.prototype._doLegacyAuth=function(){if(this.authtype!='nonsasl'&&this.authtype!='anonymous')
return false;var iq=new JSJaCIQ();iq.setIQ(this.server,'get','auth1');iq.appendNode('query',{xmlns:'jabber:iq:auth'},[['username',this.username]]);this.send(iq,this._doLegacyAuth2);return true;};JSJaCConnection.prototype._doLegacyAuth2=function(iq){if(!iq||iq.getType()!='result'){if(iq&&iq.getType()=='error')
this._handleEvent('onerror',iq.getChild('error'));this.disconnect();return;}
var use_digest=(iq.getChild('digest')!=null);var iq=new JSJaCIQ();iq.setIQ(this.server,'set','auth2');query=iq.appendNode('query',{xmlns:'jabber:iq:auth'},[['username',this.username],['resource',this.resource]]);if(use_digest){query.appendChild(iq.buildNode('digest',{xmlns:'jabber:iq:auth'},hex_sha1(this.streamid+this.pass)));}else if(this.allow_plain){query.appendChild(iq.buildNode('password',{xmlns:'jabber:iq:auth'},this.pass));}else{this.oDbg.log("no valid login mechanism found",1);this.disconnect();return false;}
this.send(iq,this._doLegacyAuthDone);};JSJaCConnection.prototype._doLegacyAuthDone=function(iq){if(iq.getType()!='result'){if(iq.getType()=='error')
this._handleEvent('onerror',iq.getChild('error'));this.disconnect();}else
this._handleEvent('onconnect');};JSJaCConnection.prototype._doSASLAuth=function(){if(this.authtype=='nonsasl'||this.authtype=='anonymous')
return false;if(this.authtype=='saslanon'){if(this.mechs['ANONYMOUS']){this.oDbg.log("SASL using mechanism 'ANONYMOUS'",2);return this._sendRaw("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>",this._doSASLAuthDone);}
this.oDbg.log("SASL ANONYMOUS requested but not supported",1);}else{if(this.mechs['DIGEST-MD5']){this.oDbg.log("SASL using mechanism 'DIGEST-MD5'",2);return this._sendRaw("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5'/>",this._doSASLAuthDigestMd5S1);}else if(this.allow_plain&&this.mechs['PLAIN']){this.oDbg.log("SASL using mechanism 'PLAIN'",2);var authStr=this.username+'@'+
this.domain+String.fromCharCode(0)+
this.username+String.fromCharCode(0)+
this.pass;this.oDbg.log("authenticating with '"+authStr+"'",2);authStr=btoa(authStr);return this._sendRaw("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>"+authStr+"</auth>",this._doSASLAuthDone);}
this.oDbg.log("No SASL mechanism applied",1);this.authtype='nonsasl';}
return false;};JSJaCConnection.prototype._doSASLAuthDigestMd5S1=function(el){if(el.nodeName!="challenge"){this.oDbg.log("challenge missing",1);this._handleEvent('onerror',JSJaCError('401','auth','not-authorized'));this.disconnect();}else{var challenge=atob(el.firstChild.nodeValue);this.oDbg.log("got challenge: "+challenge,2);this._nonce=challenge.substring(challenge.indexOf("nonce=")+7);this._nonce=this._nonce.substring(0,this._nonce.indexOf("\""));this.oDbg.log("nonce: "+this._nonce,2);if(this._nonce==''||this._nonce.indexOf('\"')!=-1){this.oDbg.log("nonce not valid, aborting",1);this.disconnect();return;}
this._digest_uri="xmpp/";this._digest_uri+=this.domain;this._cnonce=cnonce(14);this._nc='00000001';var A1=str_md5(this.username+':'+this.domain+':'+this.pass)+':'+this._nonce+':'+this._cnonce;var A2='AUTHENTICATE:'+this._digest_uri;var response=hex_md5(hex_md5(A1)+':'+this._nonce+':'+this._nc+':'+
this._cnonce+':auth:'+hex_md5(A2));var rPlain='username="'+this.username+'",realm="'+this.domain+'",nonce="'+this._nonce+'",cnonce="'+this._cnonce+'",nc="'+this._nc+'",qop=auth,digest-uri="'+this._digest_uri+'",response="'+response+'",charset=utf-8';this.oDbg.log("response: "+rPlain,2);this._sendRaw("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>"+
binb2b64(str2binb(rPlain))+"</response>",this._doSASLAuthDigestMd5S2);}};JSJaCConnection.prototype._doSASLAuthDigestMd5S2=function(el){if(el.nodeName=='failure'){if(el.xml)
this.oDbg.log("auth error: "+el.xml,1);else
this.oDbg.log("auth error",1);this._handleEvent('onerror',JSJaCError('401','auth','not-authorized'));this.disconnect();return;}
var response=atob(el.firstChild.nodeValue);this.oDbg.log("response: "+response,2);var rspauth=response.substring(response.indexOf("rspauth=")+8);this.oDbg.log("rspauth: "+rspauth,2);var A1=str_md5(this.username+':'+this.domain+':'+this.pass)+':'+this._nonce+':'+this._cnonce;var A2=':'+this._digest_uri;var rsptest=hex_md5(hex_md5(A1)+':'+this._nonce+':'+this._nc+':'+
this._cnonce+':auth:'+hex_md5(A2));this.oDbg.log("rsptest: "+rsptest,2);if(rsptest!=rspauth){this.oDbg.log("SASL Digest-MD5: server repsonse with wrong rspauth",1);this.disconnect();return;}
if(el.nodeName=='success')
this._reInitStream(this.domain,this._doStreamBind);else
this._sendRaw("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>",this._doSASLAuthDone);};JSJaCConnection.prototype._doSASLAuthDone=function(el){if(el.nodeName!='success'){this.oDbg.log("auth failed",1);this._handleEvent('onerror',JSJaCError('401','auth','not-authorized'));this.disconnect();}else
this._reInitStream(this.domain,this._doStreamBind);};JSJaCConnection.prototype._doStreamBind=function(){var iq=new JSJaCIQ();iq.setIQ(this.domain,'set','bind_1');iq.appendNode("bind",{xmlns:"urn:ietf:params:xml:ns:xmpp-bind"},[["resource",this.resource]]);this.oDbg.log(iq.xml());this.send(iq,this._doXMPPSess);};JSJaCConnection.prototype._doXMPPSess=function(iq){if(iq.getType()!='result'||iq.getType()=='error'){this.disconnect();if(iq.getType()=='error')
this._handleEvent('onerror',iq.getChild('error'));return;}
this.fulljid=iq.getChildVal("jid");this.jid=this.fulljid.substring(0,this.fulljid.lastIndexOf('/'));iq=new JSJaCIQ();iq.setIQ(this.domain,'set','sess_1');iq.appendNode("session",{xmlns:"urn:ietf:params:xml:ns:xmpp-session"},[]);this.oDbg.log(iq.xml());this.send(iq,this._doXMPPSessDone);};JSJaCConnection.prototype._doXMPPSessDone=function(iq){if(iq.getType()!='result'||iq.getType()=='error'){this.disconnect();if(iq.getType()=='error')
this._handleEvent('onerror',iq.getChild('error'));return;}else
this._handleEvent('onconnect');};JSJaCConnection.prototype._handleEvent=function(event,arg){event=event.toLowerCase();this.oDbg.log("incoming event '"+event+"'",3);if(!this._events[event])
return;this.oDbg.log("handling event '"+event+"'",2);for(var i=0;i<this._events[event].length;i++){var aEvent=this._events[event][i];if(aEvent.handler){try{if(arg){if(arg.pType){if((!arg.getNode().hasChildNodes()&&aEvent.childName!='*')||(arg.getNode().hasChildNodes()&&!arg.getChild(aEvent.childName,aEvent.childNS)))
continue;if(aEvent.type!='*'&&arg.getType()!=aEvent.type)
continue;this.oDbg.log(aEvent.childName+"/"+aEvent.childNS+"/"+aEvent.type+" => match for handler "+aEvent.handler,3);}
if(aEvent.handler.call(this,arg))
break;}
else
if(aEvent.handler.call(this))
break;}catch(e){this.oDbg.log(aEvent.handler+"\n>>>"+e.name+": "+e.message,1);}}}};JSJaCConnection.prototype._handlePID=function(aJSJaCPacket){if(!aJSJaCPacket.getID())
return false;for(var i in this._regIDs){if(this._regIDs.hasOwnProperty(i)&&this._regIDs[i]&&i==aJSJaCPacket.getID()){var pID=aJSJaCPacket.getID();this.oDbg.log("handling "+pID,3);try{if(this._regIDs[i].cb.call(this,aJSJaCPacket,this._regIDs[i].arg)===false){return false;}else{this._unregisterPID(pID);return true;}}catch(e){this.oDbg.log(e.name+": "+e.message);this._unregisterPID(pID);return true;}}}
return false;};JSJaCConnection.prototype._handleResponse=function(req){var rootEl=this._parseResponse(req);if(!rootEl)
return;for(var i=0;i<rootEl.childNodes.length;i++){if(this._sendRawCallbacks.length){var cb=this._sendRawCallbacks[0];this._sendRawCallbacks=this._sendRawCallbacks.slice(1,this._sendRawCallbacks.length);cb.fn.call(this,rootEl.childNodes.item(i),cb.arg);continue;}
this._inQ=this._inQ.concat(rootEl.childNodes.item(i));}};JSJaCConnection.prototype._parseStreamFeatures=function(doc){if(!doc){this.oDbg.log("nothing to parse ... aborting",1);return false;}
var errorTag;if(doc.getElementsByTagNameNS)
errorTag=doc.getElementsByTagNameNS("http://etherx.jabber.org/streams","error").item(0);else{var errors=doc.getElementsByTagName("error");for(var i=0;i<errors.length;i++)
if(errors.item(i).namespaceURI=="http://etherx.jabber.org/streams"){errorTag=errors.item(i);break;}}
if(errorTag){this._setStatus("internal_server_error");clearTimeout(this._timeout);clearInterval(this._interval);clearInterval(this._inQto);this._handleEvent('onerror',JSJaCError('503','cancel','session-terminate'));this._connected=false;this.oDbg.log("Disconnected.",1);this._handleEvent('ondisconnect');return false;}
this.mechs=new Object();var lMec1=doc.getElementsByTagName("mechanisms");this.has_sasl=false;for(var i=0;i<lMec1.length;i++)
if(lMec1.item(i).getAttribute("xmlns")=="urn:ietf:params:xml:ns:xmpp-sasl"){this.has_sasl=true;var lMec2=lMec1.item(i).getElementsByTagName("mechanism");for(var j=0;j<lMec2.length;j++)
this.mechs[lMec2.item(j).firstChild.nodeValue]=true;break;}
if(this.has_sasl)
this.oDbg.log("SASL detected",2);else{this.authtype='nonsasl';this.oDbg.log("No support for SASL detected",2);}
return true;};JSJaCConnection.prototype._process=function(timerval){if(!this.connected()){this.oDbg.log("Connection lost ...",1);if(this._interval)
clearInterval(this._interval);return;}
this.setPollInterval(timerval);if(this._timeout)
clearTimeout(this._timeout);var slot=this._getFreeSlot();if(slot<0)
return;if(typeof(this._req[slot])!='undefined'&&typeof(this._req[slot].r)!='undefined'&&this._req[slot].r.readyState!=4){this.oDbg.log("Slot "+slot+" is not ready");return;}
if(!this.isPolling()&&this._pQueue.length==0&&this._req[(slot+1)%2]&&this._req[(slot+1)%2].r.readyState!=4){this.oDbg.log("all slots busy, standby ...",2);return;}
if(!this.isPolling())
this.oDbg.log("Found working slot at "+slot,2);this._req[slot]=this._setupRequest(true);this._req[slot].r.onreadystatechange=JSJaC.bind(function(){if(!this.connected())
return;if(this._req[slot].r.readyState==4){this._setStatus('processing');this.oDbg.log("async recv: "+this._req[slot].r.responseText,4);this._handleResponse(this._req[slot]);if(this._pQueue.length){this._timeout=setTimeout(JSJaC.bind(this._process,this),100);}else{this.oDbg.log("scheduling next poll in "+this.getPollInterval()+" msec",4);this._timeout=setTimeout(JSJaC.bind(this._process,this),this.getPollInterval());}}},this);try{this._req[slot].r.onerror=JSJaC.bind(function(){if(!this.connected())
return;this._errcnt++;this.oDbg.log('XmlHttpRequest error ('+this._errcnt+')',1);if(this._errcnt>JSJAC_ERR_COUNT){this._abort();return false;}
this._setStatus('onerror_fallback');setTimeout(JSJaC.bind(this._resume,this),this.getPollInterval());return false;},this);}catch(e){}
var reqstr=this._getRequestString();if(typeof(this._rid)!='undefined')
this._req[slot].rid=this._rid;this.oDbg.log("sending: "+reqstr,4);this._req[slot].r.send(reqstr);};JSJaCConnection.prototype._registerPID=function(pID,cb,arg){if(!pID||!cb)
return false;this._regIDs[pID]=new Object();this._regIDs[pID].cb=cb;if(arg)
this._regIDs[pID].arg=arg;this.oDbg.log("registered "+pID,3);return true;};JSJaCConnection.prototype._sendEmpty=function JSJaCSendEmpty(){var slot=this._getFreeSlot();this._req[slot]=this._setupRequest(true);this._req[slot].r.onreadystatechange=JSJaC.bind(function(){if(this._req[slot].r.readyState==4){this.oDbg.log("async recv: "+this._req[slot].r.responseText,4);this._getStreamID(slot);}},this);if(typeof(this._req[slot].r.onerror)!='undefined'){this._req[slot].r.onerror=JSJaC.bind(function(e){this.oDbg.log('XmlHttpRequest error',1);return false;},this);}
var reqstr=this._getRequestString();this.oDbg.log("sending: "+reqstr,4);this._req[slot].r.send(reqstr);};JSJaCConnection.prototype._sendRaw=function(xml,cb,arg){if(cb)
this._sendRawCallbacks.push({fn:cb,arg:arg});this._pQueue.push(xml);this._process();return true;};JSJaCConnection.prototype._setStatus=function(status){if(!status||status=='')
return;if(status!=this._status){this._status=status;this._handleEvent('onstatuschanged',status);this._handleEvent('status_changed',status);}};JSJaCConnection.prototype._unregisterPID=function(pID){if(!this._regIDs[pID])
return false;this._regIDs[pID]=null;this.oDbg.log("unregistered "+pID,3);return true;};function JSJaCHttpBindingConnection(oArg){this.base=JSJaCConnection;this.base(oArg);this._hold=JSJACHBC_MAX_HOLD;this._inactivity=0;this._last_requests=new Object();this._last_rid=0;this._min_polling=0;this._pause=0;this._wait=JSJACHBC_MAX_WAIT;}
JSJaCHttpBindingConnection.prototype=new JSJaCConnection();JSJaCHttpBindingConnection.prototype.inherit=function(oArg){this.domain=oArg.domain||'localhost';this.username=oArg.username;this.resource=oArg.resource;this._sid=oArg.sid;this._rid=oArg.rid;this._min_polling=oArg.polling;this._inactivity=oArg.inactivity;this._setHold(oArg.requests-1);this.setPollInterval(this._timerval);if(oArg.wait)
this._wait=oArg.wait;this._connected=true;this._handleEvent('onconnect');this._interval=setInterval(JSJaC.bind(this._checkQueue,this),JSJAC_CHECKQUEUEINTERVAL);this._inQto=setInterval(JSJaC.bind(this._checkInQ,this),JSJAC_CHECKINQUEUEINTERVAL);this._timeout=setTimeout(JSJaC.bind(this._process,this),this.getPollInterval());};JSJaCHttpBindingConnection.prototype.setPollInterval=function(timerval){if(timerval&&!isNaN(timerval)){if(!this.isPolling())
this._timerval=100;else if(this._min_polling&&timerval<this._min_polling*1000)
this._timerval=this._min_polling*1000;else if(this._inactivity&&timerval>this._inactivity*1000)
this._timerval=this._inactivity*1000;else
this._timerval=timerval;}
return this._timerval;};JSJaCHttpBindingConnection.prototype.isPolling=function(){return(this._hold==0)};JSJaCHttpBindingConnection.prototype._getFreeSlot=function(){for(var i=0;i<this._hold+1;i++)
if(typeof(this._req[i])=='undefined'||typeof(this._req[i].r)=='undefined'||this._req[i].r.readyState==4)
return i;return-1;};JSJaCHttpBindingConnection.prototype._getHold=function(){return this._hold;};JSJaCHttpBindingConnection.prototype._getRequestString=function(raw,last){raw=raw||'';var reqstr='';if(this._rid<=this._last_rid&&typeof(this._last_requests[this._rid])!='undefined')
reqstr=this._last_requests[this._rid].xml;else{var xml='';while(this._pQueue.length){var curNode=this._pQueue[0];xml+=curNode;this._pQueue=this._pQueue.slice(1,this._pQueue.length);}
reqstr="<body rid='"+this._rid+"' sid='"+this._sid+"' xmlns='http://jabber.org/protocol/httpbind' ";if(JSJAC_HAVEKEYS){reqstr+="key='"+this._keys.getKey()+"' ";if(this._keys.lastKey()){this._keys=new JSJaCKeys(hex_sha1,this.oDbg);reqstr+="newkey='"+this._keys.getKey()+"' ";}}
if(last)
reqstr+="type='terminate'";else if(this._reinit){if(JSJACHBC_USE_BOSH_VER)
reqstr+="xmpp:restart='true' xmlns:xmpp='urn:xmpp:xbosh'";this._reinit=false;}
if(xml!=''||raw!=''){reqstr+=">"+raw+xml+"</body>";}else{reqstr+="/>";}
this._last_requests[this._rid]=new Object();this._last_requests[this._rid].xml=reqstr;this._last_rid=this._rid;for(var i in this._last_requests)
if(this._last_requests.hasOwnProperty(i)&&i<this._rid-this._hold)
delete(this._last_requests[i]);}
return reqstr;};JSJaCHttpBindingConnection.prototype._getInitialRequestString=function(){var reqstr="<body content='text/xml; charset=utf-8' hold='"+this._hold+"' xmlns='http://jabber.org/protocol/httpbind' to='"+this.authhost+"' wait='"+this._wait+"' rid='"+this._rid+"'";if(this.host||this.port)
reqstr+=" route='xmpp:"+this.host+":"+this.port+"'";if(this.secure)
reqstr+=" secure='"+this.secure+"'";if(JSJAC_HAVEKEYS){this._keys=new JSJaCKeys(hex_sha1,this.oDbg);key=this._keys.getKey();reqstr+=" newkey='"+key+"'";}
if(this._xmllang)
reqstr+=" xml:lang='"+this._xmllang+"'";if(JSJACHBC_USE_BOSH_VER){reqstr+=" ver='"+JSJACHBC_BOSH_VERSION+"'";reqstr+=" xmlns:xmpp='urn:xmpp:xbosh'";if(this.authtype=='sasl'||this.authtype=='saslanon')
reqstr+=" xmpp:version='1.0'";}
reqstr+="/>";return reqstr;};JSJaCHttpBindingConnection.prototype._getStreamID=function(slot){this.oDbg.log(this._req[slot].r.responseText,4);if(!this._req[slot].r.responseXML||!this._req[slot].r.responseXML.documentElement){this._handleEvent('onerror',JSJaCError('503','cancel','service-unavailable'));return;}
var body=this._req[slot].r.responseXML.documentElement;if(body.getAttribute('authid')){this.streamid=body.getAttribute('authid');this.oDbg.log("got streamid: "+this.streamid,2);}else{this._timeout=setTimeout(JSJaC.bind(this._sendEmpty,this),this.getPollInterval());return;}
this._timeout=setTimeout(JSJaC.bind(this._process,this),this.getPollInterval());if(!this._parseStreamFeatures(body))
return;if(this.register)
this._doInBandReg();else
this._doAuth();};JSJaCHttpBindingConnection.prototype._getSuspendVars=function(){return('host,port,secure,_rid,_last_rid,_wait,_min_polling,_inactivity,_hold,_last_requests,_pause').split(',');};JSJaCHttpBindingConnection.prototype._handleInitialResponse=function(slot){try{this.oDbg.log(this._req[slot].r.getAllResponseHeaders(),4);this.oDbg.log(this._req[slot].r.responseText,4);}catch(ex){this.oDbg.log("No response",4);}
if(this._req[slot].r.status!=200||!this._req[slot].r.responseXML){this.oDbg.log("initial response broken (status: "+this._req[slot].r.status+")",1);this._handleEvent('onerror',JSJaCError('503','cancel','service-unavailable'));return;}
var body=this._req[slot].r.responseXML.documentElement;if(!body||body.tagName!='body'||body.namespaceURI!='http://jabber.org/protocol/httpbind'){this.oDbg.log("no body element or incorrect body in initial response",1);this._handleEvent("onerror",JSJaCError("500","wait","internal-service-error"));return;}
if(body.getAttribute("type")=="terminate"){this.oDbg.log("invalid response:\n"+this._req[slot].r.responseText,1);clearTimeout(this._timeout);this._connected=false;this.oDbg.log("Disconnected.",1);this._handleEvent('ondisconnect');this._handleEvent('onerror',JSJaCError('503','cancel','service-unavailable'));return;}
this._sid=body.getAttribute('sid');this.oDbg.log("got sid: "+this._sid,2);if(body.getAttribute('polling'))
this._min_polling=body.getAttribute('polling');if(body.getAttribute('inactivity'))
this._inactivity=body.getAttribute('inactivity');if(body.getAttribute('requests'))
this._setHold(body.getAttribute('requests')-1);this.oDbg.log("set hold to "+this._getHold(),2);if(body.getAttribute('ver'))
this._bosh_version=body.getAttribute('ver');if(body.getAttribute('maxpause'))
this._pause=Number.max(body.getAttribute('maxpause'),JSJACHBC_MAXPAUSE);this.setPollInterval(this._timerval);this._connected=true;this._inQto=setInterval(JSJaC.bind(this._checkInQ,this),JSJAC_CHECKINQUEUEINTERVAL);this._interval=setInterval(JSJaC.bind(this._checkQueue,this),JSJAC_CHECKQUEUEINTERVAL);this._getStreamID(slot);};JSJaCHttpBindingConnection.prototype._parseResponse=function(req){if(!this.connected()||!req)
return null;var r=req.r;try{if(r.status==404||r.status==403){this._abort();return null;}
if(r.status!=200||!r.responseXML){this._errcnt++;var errmsg="invalid response ("+r.status+"):\n"+r.getAllResponseHeaders()+"\n"+r.responseText;if(!r.responseXML)
errmsg+="\nResponse failed to parse!";this.oDbg.log(errmsg,1);if(this._errcnt>JSJAC_ERR_COUNT){this._abort();return null;}
this.oDbg.log("repeating ("+this._errcnt+")",1);this._setStatus('proto_error_fallback');setTimeout(JSJaC.bind(this._resume,this),this.getPollInterval());return null;}}catch(e){this.oDbg.log("XMLHttpRequest error: status not available",1);this._errcnt++;if(this._errcnt>JSJAC_ERR_COUNT){this._abort();}else{this.oDbg.log("repeating ("+this._errcnt+")",1);this._setStatus('proto_error_fallback');setTimeout(JSJaC.bind(this._resume,this),this.getPollInterval());}
return null;}
var body=r.responseXML.documentElement;if(!body||body.tagName!='body'||body.namespaceURI!='http://jabber.org/protocol/httpbind'){this.oDbg.log("invalid response:\n"+r.responseText,1);clearTimeout(this._timeout);clearInterval(this._interval);clearInterval(this._inQto);this._connected=false;this.oDbg.log("Disconnected.",1);this._handleEvent('ondisconnect');this._setStatus('internal_server_error');this._handleEvent('onerror',JSJaCError('500','wait','internal-server-error'));return null;}
if(typeof(req.rid)!='undefined'&&this._last_requests[req.rid]){if(this._last_requests[req.rid].handled){this.oDbg.log("already handled "+req.rid,2);return null;}else
this._last_requests[req.rid].handled=true;}
if(body.getAttribute("type")=="terminate"){this.oDbg.log("session terminated:\n"+r.responseText,1);clearTimeout(this._timeout);clearInterval(this._interval);clearInterval(this._inQto);if(body.getAttribute("condition")=="remote-stream-error")
if(body.getElementsByTagName("conflict").length>0)
this._setStatus("session-terminate-conflict");this._handleEvent('onerror',JSJaCError('503','cancel',body.getAttribute('condition')));this._connected=false;this.oDbg.log("Disconnected.",1);this._handleEvent('ondisconnect');return null;}
this._errcnt=0;return r.responseXML.documentElement;};JSJaCHttpBindingConnection.prototype._reInitStream=function(to,cb,arg){this._reinit=true;cb.call(this,arg);};JSJaCHttpBindingConnection.prototype._resume=function(){if(this._pause==0&&this._rid>=this._last_rid)
this._rid=this._last_rid-1;this._process();};JSJaCHttpBindingConnection.prototype._setHold=function(hold){if(!hold||isNaN(hold)||hold<0)
hold=0;else if(hold>JSJACHBC_MAX_HOLD)
hold=JSJACHBC_MAX_HOLD;this._hold=hold;return this._hold;};JSJaCHttpBindingConnection.prototype._setupRequest=function(async){var req=new Object();var r=XmlHttp.create();try{r.open("POST",this._httpbase,async);r.setRequestHeader('Content-Type','text/xml; charset=utf-8');}catch(e){this.oDbg.log(e,1);}
req.r=r;this._rid++;req.rid=this._rid;return req;};JSJaCHttpBindingConnection.prototype._suspend=function(){if(this._pause==0)
return;var slot=this._getFreeSlot();this._req[slot]=this._setupRequest(false);var reqstr="<body pause='"+this._pause+"' xmlns='http://jabber.org/protocol/httpbind' sid='"+this._sid+"' rid='"+this._rid+"'";if(JSJAC_HAVEKEYS){reqstr+=" key='"+this._keys.getKey()+"'";if(this._keys.lastKey()){this._keys=new JSJaCKeys(hex_sha1,this.oDbg);reqstr+=" newkey='"+this._keys.getKey()+"'";}}
reqstr+=">";while(this._pQueue.length){var curNode=this._pQueue[0];reqstr+=curNode;this._pQueue=this._pQueue.slice(1,this._pQueue.length);}
reqstr+="</body>";this.oDbg.log("Disconnecting: "+reqstr,4);this._req[slot].r.send(reqstr);};function JSJaCHttpPollingConnection(oArg){this.base=JSJaCConnection;this.base(oArg);JSJACPACKET_USE_XMLNS=false;}
JSJaCHttpPollingConnection.prototype=new JSJaCConnection();JSJaCHttpPollingConnection.prototype.isPolling=function(){return true;};JSJaCHttpPollingConnection.prototype._getFreeSlot=function(){if(typeof(this._req[0])=='undefined'||typeof(this._req[0].r)=='undefined'||this._req[0].r.readyState==4)
return 0;else
return-1;};JSJaCHttpPollingConnection.prototype._getInitialRequestString=function(){var reqstr="0";if(JSJAC_HAVEKEYS){this._keys=new JSJaCKeys(b64_sha1,this.oDbg);key=this._keys.getKey();reqstr+=";"+key;}
var streamto=this.domain;if(this.authhost)
streamto=this.authhost;reqstr+=",<stream:stream to='"+streamto+"' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'";if(this.authtype=='sasl'||this.authtype=='saslanon')
reqstr+=" version='1.0'";reqstr+=">";return reqstr;};JSJaCHttpPollingConnection.prototype._getRequestString=function(raw,last){var reqstr=this._sid;if(JSJAC_HAVEKEYS){reqstr+=";"+this._keys.getKey();if(this._keys.lastKey()){this._keys=new JSJaCKeys(b64_sha1,this.oDbg);reqstr+=';'+this._keys.getKey();}}
reqstr+=',';if(raw)
reqstr+=raw;while(this._pQueue.length){reqstr+=this._pQueue[0];this._pQueue=this._pQueue.slice(1,this._pQueue.length);}
if(last)
reqstr+='</stream:stream>';return reqstr;};JSJaCHttpPollingConnection.prototype._getStreamID=function(){if(this._req[0].r.responseText==''){this.oDbg.log("waiting for stream id",2);this._timeout=setTimeout(JSJaC.bind(this._sendEmpty,this),1000);return;}
this.oDbg.log(this._req[0].r.responseText,4);if(this._req[0].r.responseText.match(/id=[\'\"]([^\'\"]+)[\'\"]/))
this.streamid=RegExp.$1;this.oDbg.log("got streamid: "+this.streamid,2);var doc;try{var response=this._req[0].r.responseText;if(!response.match(/<\/stream:stream>\s*$/))
response+='</stream:stream>';doc=XmlDocument.create("doc");doc.loadXML(response);if(!this._parseStreamFeatures(doc))
return;}catch(e){this.oDbg.log("loadXML: "+e.toString(),1);}
this._connected=true;if(this.register)
this._doInBandReg();else
this._doAuth();this._process(this._timerval);};JSJaCHttpPollingConnection.prototype._getSuspendVars=function(){return new Array();};JSJaCHttpPollingConnection.prototype._handleInitialResponse=function(){this.oDbg.log(this._req[0].r.getAllResponseHeaders(),4);var aPList=this._req[0].r.getResponseHeader('Set-Cookie');aPList=aPList.split(";");for(var i=0;i<aPList.length;i++){aArg=aPList[i].split("=");if(aArg[0]=='ID')
this._sid=aArg[1];}
this.oDbg.log("got sid: "+this._sid,2);this._connected=true;this._interval=setInterval(JSJaC.bind(this._checkQueue,this),JSJAC_CHECKQUEUEINTERVAL);this._inQto=setInterval(JSJaC.bind(this._checkInQ,this),JSJAC_CHECKINQUEUEINTERVAL);this._getStreamID();};JSJaCHttpPollingConnection.prototype._parseResponse=function(r){var req=r.r;if(!this.connected())
return null;if(req.status!=200){this.oDbg.log("invalid response ("+req.status+"):"+req.responseText+"\n"+req.getAllResponseHeaders(),1);this._setStatus('internal_server_error');clearTimeout(this._timeout);clearInterval(this._interval);clearInterval(this._inQto);this._connected=false;this.oDbg.log("Disconnected.",1);this._handleEvent('ondisconnect');this._handleEvent('onerror',JSJaCError('503','cancel','service-unavailable'));return null;}
this.oDbg.log(req.getAllResponseHeaders(),4);var sid,aPList=req.getResponseHeader('Set-Cookie');if(aPList==null)
sid="-1:0";else{aPList=aPList.split(";");var sid;for(var i=0;i<aPList.length;i++){var aArg=aPList[i].split("=");if(aArg[0]=='ID')
sid=aArg[1];}}
if(typeof(sid)!='undefined'&&sid.indexOf(':0')!=-1){switch(sid.substring(0,sid.indexOf(':0'))){case'0':this.oDbg.log("invalid response:"+req.responseText,1);break;case'-1':this.oDbg.log("Internal Server Error",1);break;case'-2':this.oDbg.log("Bad Request",1);break;case'-3':this.oDbg.log("Key Sequence Error",1);break;}
this._setStatus('internal_server_error');clearTimeout(this._timeout);clearInterval(this._interval);clearInterval(this._inQto);this._handleEvent('onerror',JSJaCError('500','wait','internal-server-error'));this._connected=false;this.oDbg.log("Disconnected.",1);this._handleEvent('ondisconnect');return null;}
if(!req.responseText||req.responseText=='')
return null;try{var response=req.responseText.replace(/\<\?xml.+\?\>/,"");if(response.match(/<stream:stream/))
response+="</stream:stream>";var doc=JSJaCHttpPollingConnection._parseTree("<body>"+response+"</body>");if(!doc||doc.tagName=='parsererror'){this.oDbg.log("parsererror",1);doc=JSJaCHttpPollingConnection._parseTree("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'>"+req.responseText);if(doc&&doc.tagName!='parsererror'){this.oDbg.log("stream closed",1);if(doc.getElementsByTagName('conflict').length>0)
this._setStatus("session-terminate-conflict");clearTimeout(this._timeout);clearInterval(this._interval);clearInterval(this._inQto);this._handleEvent('onerror',JSJaCError('503','cancel','session-terminate'));this._connected=false;this.oDbg.log("Disconnected.",1);this._handleEvent('ondisconnect');}else
this.oDbg.log("parsererror:"+doc,1);return doc;}
return doc;}catch(e){this.oDbg.log("parse error:"+e.message,1);}
return null;;};JSJaCHttpPollingConnection.prototype._reInitStream=function(to,cb,arg){this._sendRaw("<stream:stream xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client' to='"+to+"' version='1.0'>",cb,arg);};JSJaCHttpPollingConnection.prototype._resume=function(){this._process(this._timerval);};JSJaCHttpPollingConnection.prototype._setupRequest=function(async){var r=XmlHttp.create();try{r.open("POST",this._httpbase,async);if(r.overrideMimeType)
r.overrideMimeType('text/plain; charset=utf-8');r.setRequestHeader('Content-Type','application/x-www-form-urlencoded');}catch(e){this.oDbg.log(e,1);}
var req=new Object();req.r=r;return req;};JSJaCHttpPollingConnection.prototype._suspend=function(){};JSJaCHttpPollingConnection._parseTree=function(s){try{var r=XmlDocument.create("body","foo");if(typeof(r.loadXML)!='undefined'){r.loadXML(s);return r.documentElement;}else if(window.DOMParser)
return(new DOMParser()).parseFromString(s,"text/xml").documentElement;}catch(e){}
return null;};var JSJaC={Version:'$Rev: 456 $',require:function(libraryName){document.write('<script type="text/javascript" src="'+libraryName+'"></script>');},load:function(){var includes=['xmlextras','jsextras','crypt','JSJaCConfig','JSJaCConstants','JSJaCCookie','JSJaCJSON','JSJaCJID','JSJaCBuilder','JSJaCPacket','JSJaCError','JSJaCKeys','JSJaCConnection','JSJaCHttpPollingConnection','JSJaCHttpBindingConnection','JSJaCConsoleLogger'];var scripts=document.getElementsByTagName("script");var path='./';for(var i=0;i<scripts.length;i++){if(scripts.item(i).src&&scripts.item(i).src.match(/JSJaC\.js$/)){path=scripts.item(i).src.replace(/JSJaC.js$/,'');break;}}
for(var i=0;i<includes.length;i++)
this.require(path+includes[i]+'.js');},bind:function(fn,obj,arg){return function(){if(arg)
fn.apply(obj,arg);else
fn.apply(obj);};}};if(typeof JSJaCConnection=='undefined')
JSJaC.load();

function Auction(){this.id=0;this.name='';this.startTime=0;this.closeTime=0;this.type=1;this.isPublic=1;this.status='';this.price=0;this.startPrice=0;this.guaranteePrice=0;this.bidoPrice='hidden';this.bidoPriceMetText='';this.minPrice=0;this.lastPrice=0;this.lastTime=0;this.updatePriceTimerId;this.nextBid=0;this.bids=new BidsCollection(this);this.bidsCount=0;this.chat;this.userNick='';this.userId=0;this.userBid=0;this.userProxy=0;this.userWinning=false;this.userScheduledBid=0;this.userScheduledBidTime=0;this.userTriggerBid=0;this.userTriggerNeedBid=0;this.highBidder='';this.highBidderId=0;this.changes={};this.pauseReason='';this.messageBody;this.messageTimerId;this.messageDelay=7000;this.scales=[];this.defPercent=10;this.offerMode=0;this.offerTimer=0;this.buyItNowPrice=0;this.binOfferShowed=false;this.binBidPlaced=false;this.locationHome=true;this.priceFormat=1;this.videoStartTime=0;this.videoEndTime=0;this.chatStatus=0;this.colorRed="#990000";this.colorGreen="#009900";this.colorBlack="#000000";this.init=function(opt){for(var i in opt){this[i]=opt[i];}
this.messageBody=$('#bidStatus');}
this.closeAuction=function(){this.status='closed';if(this.userWinning&&$('#sound_off')[0]&&$('#sound_off')[0].className=="sound-active"){playSound('win');}
var left=$('.main_auction_block .ablock_header .left img')[0];if(left){if(this.bids.length()>0&&this.bidoPrice!='hidden'&&this.price>=this.bidoPrice){left.src=imagePath+'/images/soldAuction.png';$('#sold_image').show();}else{left.src=imagePath+'/images/closedAuction.png';}
left.alt='Closed Auction';left.title='Closed Auction';}
$('#auctionTitle').html('Closed auction: ');$('#guarantee_price').hide();var children=$('.main_auction_block .bid-block').children();for(var i=0;i<children.length;i++){var child=children[i];if(child.className!='bid_status_text'&&child.className!='ablock_header'&&child.id!='ablock_info'&&child.id!='ablock_history'&&child.className!='visitor_link'){$(children[i]).remove();}}
$('#ablockInitBid').html('Closing price:');if(this.price==0){$('#currentBid').html('No bids');}
if($('#ablockStartBid').length>0)$('#ablockStartBid').remove();if($('#ablockCurrentBid').length>0)$('#ablockCurrentBid').remove();if($('#currentBidAd').length>0)$('#currentBidAd').remove();$('#userProxy').html('US $'+formatBidPrice(this.userProxy,this.priceFormat));if(this.bids.length()>0&&this.bidoPrice!='hidden'&&this.price>this.bidoPrice){var bid=this.bids.getLastNonRetracted();$('#ablock_info').append('<tr><td style="width: 100px;"><span style="font-size:12px;">Winner:</span></td><td>'+
(this.userNick=='visitor'?'<strong>'+bid.nick+'</strong>':'<a href="'+httpUrl+'/Profile/'+bid.nick+'">'+bid.nick+'</a>')
+'</td></tr>');}
var startTime=new Date(this.startTime*1000);var closeTime=new Date(this.closeTime*1000);$("#ablock_info").append('<tr><td style="width: 100px;"><span style="margin-top: 7px;">Start date:</span></td>'+'<td nowrap><span>'+startTime.format("mmm dd yyyy, hh:MM tt")+'</span></td></tr>'+
(this.closeTime?'<tr><td style="width: 100px;"><span style="margin-top: 7px;">Close date:</span></td>'+'<td nowrap><span>'+closeTime.format("mmm dd yyyy, hh:MM tt")+'</span></td></tr>':''));if(this.userNick=='visitor'){$('.main_auction_block .live_visitor_link').remove();$('#bidHistoryLink').show();}
if(this.chat){this.chat.toggleSound(false);}
if($('#chat_sound_on').length>0)$('#chat_sound_on').remove();if($('#chat_sound_off').length>0)$('#chat_sound_off').remove();$('#tab-content-desc-table-status').html('CLOSED');if(this.buyItNowPrice){$('#buyNow').hide();}
if($('#timerTitle').length){document.location.reload();}else{closeWindow('dynamicOfferWindow');}}
this.openAuction=function(timer){if(this.status=='not started'){this.status='opened';var left=$('.main_auction_block .ablock_header .left img')[0];if(left){left.src=imagePath+'/images/atAuction.png';left.alt='At Auction';left.title='At Auction';}
$('#ablockInitBid').html('Current bid:');$('#auctionTitle').html('Live auction: ');$('#ablockStartBid').show();$('#ablockCurrentBid').show();$('#ablockReserve').show();$('#ablockTimerDate').hide();$('#ablockTimerTitle').html('Estimated time for Auction to end:');$('#pauseAuction').show();$('#guarantee_price').show();$('#bblockSound').show();$('#bblockMsg').hide();$('#userProxyHelp').html('(<a href="javascript:void(0)">?</a>)')
$('#userProxyHelp a').unbind().mouseover(function(){showHelpProcess(helpTexts.maxBid,this)}).click(function(){showHelpProcess(helpTexts.maxBid,this)});$('#userProxyHelp').show();if(this.userNick!='visitor'){$('#bidHistoryLink').show();}
$('#no-comments-text').text("No comments from our Expert Members.").css({"padding":"0px","vertical-align":"middle","text-align":"center"});if($('#comment_0')[0])$($('#comment_0')[0]).remove();if($('#biddingWindow')[0])$($('#biddingWindow')[0]).remove();$('.addCommentButton').remove();$('#commentariesClosed').show();if(this.type==2){$('#bidButtonContainer').show();this.lastPrice=this.startPrice;this.lastTimer=timer;this.updatePrice();}
if($('#timerTitle').length){$('#timerTitle').html('closes in ');}
if($('#cashback').length){$('#cashback').remove();}
$('#bidButton').show();}
if(this.status=='paused'){this.status='opened';this.pause(false);}}
this.setStatus=function(status,timer){if(status=='closed'&&(this.status=='opened'||this.status=='extended'||this.status=='not started')){this.closeAuction();}
if(status=='deleted'&&this.status!='deleted'){document.location.reload();}
if(status=='opened'){this.openAuction(timer);}
if(status=='paused'){this.status=status;this.pause(true);}
this.checkVideoTimer();}
this.setChatStatus=function(status){if(this.chatStatus!=status){this.chatStatus=status;if(this.id==$('.chatSelect').val()){if(this.chatStatus=='opened'){$('.chatConnectionStatus').css('text-align','center');$('.chatMessageBox, .chatSendButton').attr('disabled',!chatAvailable);$('.chatConnectionStatus').html(auctionTexts.chatOpened);}else{$('.chatMessageBox, .chatSendButton').attr('disabled',!chatAvailable);app.mainChat.clearUsers();}
app.mainChat.showLoginLink();}}}
this.setStartPrice=function(response){this.startPrice=response.start_price;if(this.type==2&&this.status=='opened'&&this.minPrice){this.lastPrice=response.current_price;this.lastTimer=response.timer;this.updatePrice();}}
this.updatePrice=callback(this,function(){this.setPrice(this.getNextBid());this.nextBid=this.price;$('#bid').attr('value',this.nextBid);$('#currentBid').html('US $'+formatBidPrice(this.price,this.priceFormat));window.clearTimeout(this.updatePriceTimerId);this.updatePriceTimerId=window.setTimeout(this.updatePrice,1000);})
this.showUpcomingBuyItNow=function(bid){if(bid>=this.buyItNowPrice){showBinWindow(this.id,this.buyItNowPrice,this.name,'AuctionBIN');if(app.main_auction.id==this.id){$('#bidButtonLoad').hide();$('#bidButton').fadeIn();}
$('#auction_block_'+this.id).find('.bidButtonLoad').hide();$('#auction_block_'+this.id).find('.bidButton').fadeIn();$('#bidButtonLoad_'+this.id).hide();$('.bidButton_'+this.id).fadeIn();if($('#bidWindowAuctionId').val()==this.id){$('#bid_block_'+this.id+' .button-popup').fadeIn();}
return true;}
return false;}
this.placeBid=function(bid,isOffer,callback){if(this.buyItNowPrice&&this.status=='not started'&&this.showUpcomingBuyItNow(bid)){return false;}
var query={"auction":this.id,"bid":bid,"is offer":isOffer};sendMessage(JSJaCJSON.toString(query),callback);return true;}
this.scheduleBid=function(bid,time,callback){var query={"auction":this.id,"schedule bid":bid,"time":time};sendMessage(JSJaCJSON.toString(query),callback);}
this.triggerBid=function(bid,need_bid,callback){var query={"auction":this.id,"trigger bid":bid,"need bid":need_bid};sendMessage(JSJaCJSON.toString(query),callback);}
this.cancelBid=function(type,callback){var query={"auction":this.id,"cancel bid":type};sendMessage(JSJaCJSON.toString(query),callback);}
this.setProxy=function(response){if(response.price){this.setPrice(response.price);}
if(response.high_bidder){this.highBidderId=response.high_bidder;}
this.binBidPlaced=response.bin?true:false;this.userProxy=response.proxy?response.proxy:0;this.showMessage(response);}
this.setScheduledBid=function(response){this.showMessage(response);if(response.result>=0){this.userScheduledBid=response.scheduled_bid?response.scheduled_bid:0;this.userScheduledBidTime=response.scheduled_bid_time?response.scheduled_bid_time:0;}}
this.setTriggerBid=function(response){this.showMessage(response);if(response.result>=0){this.userTriggerBid=response.trigger_bid?response.trigger_bid:0;this.userTriggerNeedBid=response.trigger_need_bid?response.trigger_need_bid:0;}}
this.getMessageColor=function(response){var color=(response.result==0||response.result==2||response.result==5)?this.colorGreen:this.colorRed;if(this.status=='not started'){color=this.colorBlack;}
if(response.result==-2){color=this.colorRed;}
if(response.result==3||response.result==4||response.result==6||response.result==7){color=this.colorRed;}
return color;}
this.showMessage=function(response){if(response.message&&typeof(response.result)!='undefined'){if(response.result==3&&typeof(showBidWindow)=='function'){showBidWindow(true,true);}
this.messageBody.css('color',this.getMessageColor(response));this.messageBody.html(response.message);window.clearTimeout(this.messageTimerId);this.messageTimerId=window.setTimeout('$("#bidStatus").text("")',this.messageDelay);}}
this.addBids=function(bids){var bid;for(var i=0;i<bids.length;i++){bid=bids[i];if(this.bidoPrice&&bid.amount>=this.bidoPrice){this.bids.add({'id':'BidoPriceMet','text':helpTexts['bidoPriceMetRow'].replace('{$bido_price}',formatBidPrice(this.bidoPrice))});}
if(this.bids.add(bid)){if(!bid.retracted){if(this.userId==bid.user){this.userBid=bid.amount;if(this.userProxy<bid.amount){this.userProxy=bid.amount;}}
if(this.price<=bid.amount&&!bid.retract_in_history){this.setPrice(bid.amount);this.highBidder=bid.nick;this.highBidderId=bid.user;}}}}
this.bidsCount=this.bids.length();}
this.getPriceColor=function(){if(this.userWinning&&(this.userBid>=this.bidoPrice||this.userProxy>=this.bidoPrice||this.bidoPrice=='hidden')){return'#00AA00';}
if((this.userBid||this.userProxy)&&this.status!='not started'){return'#AA0000';}else{return'#000000';}}
this.update=function(eff){if(this.status=='closed'){return false;}
$('#userProxyHelp').show();var userProxyValue='US $'+formatBidPrice(this.userProxy,this.priceFormat);if(this.type==1){if(this.status=='opened'||this.status=='paused'||this.status=='extended'){if(this.price<this.userProxy){$('#userProxyTitle').html('Your max bid:');}else{$('#userProxyTitle').html('Your max bid:');}}
if(this.userProxy<=0){userProxyValue='You have not bid yet';$('#userProxyHelp').hide();}}
$('#userProxy').html(userProxyValue);if(this.status=='opened'&&this.bidoPrice<=this.price)
{$('#userProxyTr').show();}
$('#startBid').html('US $'+formatBidPrice(this.startPrice,this.priceFormat));if(this.userBid>0){$('#userBid').html('US $'+formatBidPrice(this.userBid,this.priceFormat));}
var priceToCompare=(this.status=='not started'?this.userProxy:this.price);var needToCompare=(this.status=='not started'&&!(this.userProxy)?false:true);if(this.bidoPrice=='hidden'){$('#bidoPriceMet').html('Not met');}else if((this.bidoPrice>priceToCompare)&&needToCompare){$('#bidoPriceMet').html('US $'+formatBidPrice(this.bidoPrice)+' not met');}else if((this.bidoPrice<=priceToCompare)&&needToCompare){$('.bidoPrice').text('$'+formatBidPrice(this.bidoPrice));$('#bidoPriceMet').html(this.bidoPriceMetText.replace('{$bido_price}',formatBidPrice(this.bidoPrice)));}else{$('.bidoPrice').text('$'+formatBidPrice(this.bidoPrice));$('#bidoPriceMet').html('US $'+formatBidPrice(this.bidoPrice));}
this.nextBid=this.getNextBid();if($('#bidWindow').css('display')=='none'){$('#bid').attr('value',this.nextBid);}
if(this.price){var bin='';if(this.bids.length()>0&&this.bids.getLastNonRetracted().buy_it_now){bin=' (<span class="help-initiator" onmouseover="showHelpProcess(helpTexts.binBid, this);" onmouseout="cancelHelpShow();" onclick="showHelp(helpTexts.binBid, this);">bin</span>)';}
$('#currentBid').html('US $'+formatBidPrice(this.price,this.priceFormat));if($('#currentBid ~ span').attr('class')!='help-initiator'){$('#currentBid').after(bin);}
$('#currentBidAd').hide();}else{$('#currentBidAd').show();}
if(this.buyItNowPrice>0&&this.price>=Math.ceil(this.buyItNowPrice*app.config.binOfferPercent)){$('#buyNow').remove();var binWindowOpened=$('.main_auction_block .buyItNowWindow').css('display')!='none';$('.main_auction_block .buyItNowWindow').remove();if(binWindowOpened){$('#bidButtonContainer').show();}
if(!this.binBidPlaced){var removedBinHtml='N/A (<span class="help-initiator" onmouseover="showHelpProcess(tabHelpTexts.removed_bin, this);" onmouseout="cancelHelpShow();" onclick="expandStop(event); showHelp(tabHelpTexts.removed_bin, this);">?</span>)';$('#buyItNowPrice').html(removedBinHtml);}}
if(this.userId&&this.highBidderId==this.userId){if(!this.userWinning){this.userWinning=true;if(eff){playColor('high',5000,$('span.currentPrice'));}}}else{if(this.userWinning){this.userWinning=false;if(eff){playColor('out',5000,$('span.currentPrice'));if($('#sound_off')[0]&&$('#sound_off')[0].className=="sound-active"){playSound('outbid');}}}}
$('span.currentPrice').css('color',this.getPriceColor());var len=this.bids.length();if(len>0){$('#bidsCount').html('('+len+')');$('#bidHistoryLink').show();}
if(this.price>Math.ceil(this.buyItNowPrice*app.config.binOfferPercent)){$('#buyNow').hide();}
if(bidHistory.auction.id==this.id&&bidHistory.isVisible()){bidHistory.update();}
if(typeof(app.live_auctions[this.id])!='undefined'){app.live_auctions[this.id].userProxy=this.userProxy;app.live_auctions[this.id].update();}}
this.updateOffer=function(){var offerBid=getOfferPrice();if(this.nextBid>offerBid||this.userProxy>=offerBid||(this.status!='opened'&&this.status!='extended')){closeWindow('dynamicOfferWindow');return;}
$('#offer-price').html(offerBid);$('#acceptOfferButton').show();if(this.offerMode){setCountdownTimer('offer-timer',this.offerTimer);}else{this.offerMode=1;startCountdown('offer-timer',this.offerTimer,function(){this.offerTimer=0;this.offerMode=0;closeWindow('dynamicOfferWindow');},5);var wnd=$('#dynamicOfferWindow');$('body').append(wnd);displayWindow(wnd,250,0,true);}}
this.increasePriceInScale=function(price){var percent=this.defPercent;for(var i=0;i<this.scales.length;i++){if(price>=Number(this.scales[i].scale)){percent=Number(this.scales[i].percent);}else{break;}}
var minNextPrice=Math.ceil(price+price*percent/100);if(this.bidsCount==1&&(minNextPrice-price<10))
{minNextPrice=price+10;}
return minNextPrice;}
this.getNextBid=function(){var nextBid=0;switch(this.type){case 1:if(this.status=='not started'){nextBid=Math.max(this.userProxy+1,this.startPrice);}else{if(this.price<this.startPrice){nextBid=this.startPrice;}else{if(this.highBidderId==this.userId&&this.bidoPrice!='hidden'&&this.price>=this.bidoPrice){nextBid=this.userProxy+1;}else{nextBid=this.increasePriceInScale(this.price);if(this.guaranteePrice>0&&this.price<=this.guaranteePrice&&nextBid>this.guaranteePrice){nextBid=this.guaranteePrice+1;}}}}
break;case 2:var currentTime=_timer.timer.time;nextBid=Math.ceil(currentTime*(this.lastPrice-this.minPrice)/this.lastTimer+this.minPrice);break;case 3:case 4:nextBid=Math.max(this.userProxy+1,2);break;}
return nextBid;}
this.pause=function(pause){if(pause){pauseCountdown('timer',true);$('#bidWindow').hide();$('#bidButtonContainer').hide();$('#pauseReason').html(this.pauseReason);$('#pauseWindow').show();}else{pauseCountdown('timer',false);$('#pauseWindow').hide();$('#bidButtonContainer').show();}}
this.recalculate=function(){this.setPrice(0);this.userBid=0;this.highBidder='';this.highBidderId=0;this.userWinning=false;this.bids.forEach(function(item){if(!item.retracted){if(this.price<=item.amount){this.setPrice(item.amount);this.highBidder=item.nick;this.highBidderId=item.user;}
if(this.userId==item.user){this.userBid=item.amount;}}},this);if(this.highBidderId==this.userId){var query={"auction":this.id,"info":2};sendMessage(JSJaCJSON.toString(query));}else{this.userProxy=this.userBid;}}
this.setRetracted=function(bids){this.bids.setRetracted(bids);this.recalculate();this.update();if(bidHistory.auction.id==this.id){bidHistory.clear();bidHistory.update();}}
this.checkStatus=callback(this,function(){if(_timer.timer&&_timer.timer.time<=0&&(this.status=='not started'||this.status=='opened'||this.status=='extended')){if(connected){getAuctionInfo();}}
window.setTimeout(this.checkTimer,15000);})
this.checkTimer=callback(this,function(){if(_timer.timer&&_timer.timer.time<=0&&this.status!='closed'&&this.status!='deleted'&&this.status!='frozen'){$('#refreshBrowser').text('Please refresh your browser');}})
this.checkVideoTimer=callback(this,function(){switch(this.status){case'not started':if(this.videoStartTime!="now"){if(!_timer['video_start_timer']){startCountdown('video_start_timer',this.videoStartTime,this.checkVideoTimer);}else if(_timer['video_start_timer'].time<=0){$('#auction_video').show();}}else{$('#auction_video').show();}
break;case'opened':case'paused':case'extended':$('#auction_video').show();break;case'closed':if(!_timer['video_stop_timer']){if(this.videoEndTime!="never"){startCountdown('video_stop_timer',this.videoEndTime,this.checkVideoTimer);}
$('#auction_video').show();}else if(_timer['video_stop_timer'].time<=0){$('#auction_video').html(defaultVideoCode);}
break;case'deleted':$('#auction_video').html(defaultVideoCode);break;}})
this.needShowBidoPriceNotMetHelp=function(){return(this.bidoPrice=='hidden'||(this.bidoPrice>38&&this.bidoPrice>this.price))}
this.setPrice=function(value){this.price=value;if(app.tabs&&app.tabs.live){app.tabs.live.updatePrice(this.id,this.price);}}}
function BidsCollection(auction){this.items=[];this.lines=[];this.auction=auction;this.add=function(item){if(!this.getLine(item.id)){for(var i in this.lines){if(this.lines[i].content.id=='BidoPriceNotMet'){this.lines.splice(i,1);break;}}
if(item.id=='BidoPriceMet'){this.lines.push({'type':'info','content':item});}else{var lastNonRetracted=this.getLastNonRetracted();if(lastNonRetracted&&lastNonRetracted.amount==item.amount&&!item.retracted){item.highest=true;lastNonRetracted.highest=false;}
if(item.buy_it_now){this.auction.binBidPlaced=true;}
item.nick=cutText(item.nick,35);this.items.push(item);this.lines.push({'type':'bid','content':item});}
if(this.auction.needShowBidoPriceNotMetHelp()){this.lines.push({'type':'info','content':{'id':'BidoPriceNotMet','text':helpTexts['bidoPriceNotMetRow']}});}
return true;}
return false;}
this.setRetracted=function(bids){for(var i=0;i<bids.length;i++){var bid=this.getItem(bids[i].id);if(bid){bid.retracted=true;if(bids[i].hold){bid.hold=true;}}}}
this.getItem=function(id){for(var i=0;i<this.length();i++){if(this.items[i].id==id){return this.items[i];}}
return false;}
this.getLine=function(id){for(var i=0;i<this.linesCount();i++){if(this.lines[i].content.id==id){return this.lines[i];}}
return false;}
this.getLastNonRetracted=function(){for(var i=this.length()-1;i>=0;i--){if(!this.items[i].retracted){return this.items[i];}}
return false;}
this.length=function(){return this.items.length;}
this.linesCount=function(){return this.lines.length;}
this.getBidsForPage=function(number,rowsPerPage){var bids=[];var pagesCount=Math.ceil(this.linesCount()/rowsPerPage);var rest=pagesCount*rowsPerPage-this.linesCount();var start=Math.max(rowsPerPage*(pagesCount-number)-rest,0);var end=rowsPerPage*(pagesCount-number+1)-rest;for(var i=start;i<end;i++){bids.push(this.lines[i]);}
return bids;}
this.getBids=function(number,rowsPerPage){var bids=[];for(var i=0;i<this.linesCount();i++){bids.push(this.lines[i]);}
return bids;}
this.forEach=function(handler,thisObj){for(var i in this.items){handler.call(thisObj,this.items[i]);}}}
function BidHistory(){this.auction={};this.body;this.table=[];this.page=1;this.rowsPerPage=10;this.emptyLabel;this.visible=false;this.auctionNameTruncate=36;this.canManageUsers=false;this.init=function(){this.body=$('#bidHistory');$('body').append(this.body);this.emptyLabel=$('#bidHistoryEmptyLabel')[0];if(this.auctionNameTruncate&&this.auctionNameTruncate<this.auction.name.length){$('#bidHistoryAuctionName').text(this.auction.name.substring(0,this.auctionNameTruncate)+'...');}else{$('#bidHistoryAuctionName').text(this.auction.name);}
this.initTable();}
this.initTable=function(){var canManageUsers=this.canManageUsers;this.addColumn('Name','',true,function(bid){if(canManageUsers){return'<a href="'+httpUrl+'/Profile/'+bid.nick+'">'+bid.nick+'</a>';}else{return bid.nick;}});this.addColumn('Date','style="white-space: nowrap; width: 125px;"',true,function(bid){return bid.time;});this.addColumn('Bid amount, US $','style="text-align: right; width: 125px;//padding-right: 20px"',true,function(bid,auction){var isBin='';var highest='';var retracted='';var isGuarantee='';var isAbsolute='';var originalAmount='';if(bid.is_proxy){highest='(<span class="help-initiator" onmouseover="showHelpProcess(helpTexts.proxyBid, this);" onmouseout="cancelHelpShow();" onclick="showHelp(helpTexts.proxyBid, this);">p</span>) ';}else if(bid.highest){highest='(<span class="help-initiator" onmouseover="showHelpProcess(helpTexts.sameBids, this);" onmouseout="cancelHelpShow();" onclick="showHelp(helpTexts.sameBids, this);">?</span>) ';}
if(bid.retracted||bid.retract_in_history){if(bid.hold){retracted='(<span class="help-initiator" onmouseover="showHelpProcess(helpTexts.retractedHoldBid, this);" onmouseout="cancelHelpShow();" onclick="showHelp(helpTexts.retractedHoldBid, this);">h</span>) ';}else{retracted='(<span class="help-initiator" onmouseover="showHelpProcess(helpTexts.retractedBid, this);" onmouseout="cancelHelpShow();" onclick="showHelp(helpTexts.retractedBid, this);">r</span>) ';}}
if(bid.buy_it_now){isBin=' (<span class="help-initiator" onmouseover="showHelpProcess(helpTexts.binBid, this);" onmouseout="cancelHelpShow();" onclick="showHelp(helpTexts.binBid, this);">bin</span>)';}
if(bid.guarantee){isGuarantee='(<span class="help-initiator" onmouseover="showHelpProcess(helpTexts.guaranteeBid, this);" onmouseout="cancelHelpShow();" onclick="showHelp(helpTexts.guaranteeBid, this);">g</span>) ';}
if(bid.absolute&&auction.isPublic){isAbsolute='(<span class="help-initiator" onmouseover="showHelpProcess(helpTexts.absoluteBid, this);" onmouseout="cancelHelpShow();" onclick="showHelp(helpTexts.absoluteBid, this);">a</span>) ';}
if(bid.overbid){originalAmount='<span style="text-decoration: line-through;">'+'$'+formatBidPrice(bid.amount)+'</span> ';var amount=bid.overbid;}else{var amount=bid.amount;}
return retracted+highest+isGuarantee+isAbsolute+originalAmount+'$'+formatBidPrice(amount)+isBin;});}
this.setAuction=function(auction){this.auction=auction;this.table=[];this.page=1;$('#bidHistoryHead th, #bidHistoryHead td').remove();}
this.toggleHeadColumn=function(column,visible){var display=visible?'table-cell':'none';if($.browser.msie&&visible){display='block';}
$(column).css('display',display);}
this.addColumn=function(name,attr,enabled,get){this.table.push({'name':name,'attr':attr,'enabled':enabled,'get':get});this.toggleHeadColumn($('<th '+attr+'>'+name+'</th>').appendTo(this.body.find('#bidHistoryHead')[0]),enabled);}
this.enableColumn=function(name,enabled){for(var i=0;i<this.table.length;i++){if(this.table[i].name==name){this.table[i].enabled=enabled;this.toggleHeadColumn(this.body.find('#bidHistoryHead th')[i],enabled);break;}}
this.clear();this.update();}
this.isVisible=function(){return this.visible;}
this.setVisible=function(visible){this.visible=visible;if(visible){this.body.css('display','');}else{this.body.css('display','none');}}
this.show=function(){this.update();this.center();this.body.draggable({handle:'.ui-drag-bar',cancel:'td'});this.body.bgiframe();this.setVisible(true);}
this.hide=function(){this.setVisible(false);}
this.center=function(){var pos=centerPos(this.body.width(),this.body.height());this.body.css('left',pos.x-100+'px');this.body.css('top',pos.y+'px');}
this.update=function(){try{var bids=this.auction.bids.getBids();if(bids.length==0){if(!$('#bidHistoryEmptyLabel').length){this.emptyLabel='<tr id="bidHistoryEmptyLabel"><td colspan="3">No bids.</td></tr>';this.body.find('.list').append(this.emptyLabel);}
return false;}
this.updateRows(bids);$('#bid_bottom_help').toggle(this.auction.needShowBidoPriceNotMetHelp());}catch(ex){}}
this.updatePager=function(){var bidsCount=this.auction.bids.length();if(bidsCount>this.rowsPerPage){var pager='<p class="pager">Page: ';var pagesCount=Math.ceil(bidsCount/this.rowsPerPage);var range=Math.ceil(this.page/10);if(range>1){var num=Number(this.page)-10;pager+='<a onclick="bidHistory.switchPage('+num+')" href="javascript:void(0);">Prev 10</a> ';}
for(var i=(range-1)*10+1;i<=Math.min(range*10,pagesCount);i++){if(i==this.page){pager+='<b>'+i+'</b> ';}else{pager+='<a onclick="bidHistory.switchPage('+i+')" href="javascript:void(0);">'+i+'</a> ';}}
if(range*10<pagesCount){var num=Math.min(Number(this.page)+10,pagesCount);pager+='<a onclick="bidHistory.switchPage('+num+')" href="javascript:void(0);">Next 10</a> ';}
pager+='</p>';var oldPager=this.body.find('.pager');if(oldPager.length==0){$(this.body.find('.list')).before(pager);}else{oldPager.replaceWith(pager);}}else{$('#bidHistory').find('.pager').hide();}}
this.updateRows=function(bids){if(this.emptyLabel){$(this.emptyLabel).remove();this.emptyLabel=null;}
$('#bid_BidoPriceNotMet').remove();var newRows=[];for(var i=0;i<bids.length;i++){if(!document.getElementById('bid_'+bids[i].content.id)){newRows.push(bids[i]);}}
for(var i=0;i<newRows.length;i++){if(newRows[i].type=='bid'){var newRow=this.getRow(newRows[i].content);}else{var newRow=this.getInfoRow(newRows[i].content);}
$(this.body.find('tr')[0]).after(newRow);}}
this.getRow=function(bid){var className='';if(bid.user==this.auction.userId){className=' class="past"';}
if(bid.retracted){className=' class="deleted"';}else if(bid.retract_in_history){className=' class="retract-in-history"';}
var row='<tr'+className+' id="bid_'+bid.id+'">';for(var i=0;i<this.table.length;i++){if(this.table[i].enabled){row+='<td '+this.table[i].attr+'>'+this.table[i].get(bid,this.auction)+'</td>';}}
return row+'</tr>';}
this.getInfoRow=function(info){var count=0;for(var i=0;i<this.table.length;i++){if(this.table[i].enabled){count++;}}
var row='<tr class="info" id="bid_'+info.id+'">';row+='<td colspan="'+count+'">'+info.text+'</td>';return row+'</tr>';}
this.switchPage=function(page){this.page=page;this.clear();this.update();}
this.clear=function(){if(typeof this.body!='undefined')
{var rows=this.body.find('tr');for(var i=1;i<rows.length;i++){if(rows[i]){$(rows[i]).remove();}}}}}
function callback(obj,method){return function(){return method.apply(obj,arguments);}}

var con;var resource='';var userJID='';var userName='';var userPass='';var connected=false;var reconnectAttempts=1;var reconnectDelay=0;var chatAvailable=false;var notifyChatAvailable=new Notification();var notifyConnected=new Notification();var POLLINTERVAL=15000;var confs={'info':{'jid':'','msg_id':'','nick':''},'chat':{'jid':'','msg_id':'','nick':''},'ticker':{'jid':'','msg_id':'','nick':''}};var chats={};function initConnection(register){register=register||false;try{if(!con||register){showConnectionStatus('connecting');}else{showConnectionStatus('reconnecting');}
if(con&&con.connected()){con.disconnect();}
con=new JSJaCHttpBindingConnection({'httpbase':"/http-bind/",'timerval':POLLINTERVAL,'oDbg':oDbg});setupConnection();var oArgs={"domain":SITE_NAME,"username":userJID,"pass":userPass,"resource":resource,"register":register};con.connect(oArgs);}catch(ex){oDbg.log('[initConnection] error: '+ex.toString(),1);}}
function setupConnection(){con.registerHandler('onconnect',handleConnected);con.registerHandler('ondisconnect',handleDisconnected);con.registerHandler('onerror',handleError);con.registerHandler('presence',handlePresence);con.registerHandler('message',handleMessage);con.setPollInterval(POLLINTERVAL);}
function suspendConnection(){try{if(typeof con!='undefined'&&con&&con.connected()&&con.suspend){con.suspend();}}catch(ex){}}
function handleConnected(){oDbg.log('Connected',2);connected=true;notifyConnected.send();showConnectionStatus('connected');if(typeof window['spamAuction']=='function'){spamAuction();}
con.send(new JSJaCPresence());}
function handleDisconnected(){oDbg.log('Disconnected',2);connected=false;chatAvailable=false;}
function handleError(error){oDbg.log('Connection error: \nCode: '+error.getAttribute('code')+"\nType: "+error.getAttribute('type')+"\nCondition: "+error.firstChild.nodeName.htmlEnc(),1);if(error.firstChild&&error.firstChild.nodeName=="not-authorized"){initConnection(true);}else{reconnect();}}
function reconnect(){try{oDbg.log('Reconnect',0);reconnectAttempts++;reconnectDelay=Math.min(reconnectDelay+100,10000);window.setTimeout("initConnection()",reconnectDelay);}catch(ex){}}
function showConnectionStatus(status){if(status=='connecting'||status=='reconnecting'){$('.connectionStatus').html('Loading...');}
if(status=='connected'){$('.connectionStatus').html('');}}
function handlePresence(presence){if(!resource){resource=presence.getTo().substr(presence.getTo().indexOf('/')+1);}
var from=cutResource(presence.getFrom());var type=presence.getType();var show=presence.getShow();oDbg.log("[Presence] from: "+presence.getFrom()+", type: "+type+", show: "+show+"}",2);if(presence.getFrom()==userJID+'@'+SITE_NAME+'/'+resource){onConnect();}
if(app.mainChat&&confs.chat&&from==confs.chat.jid){if(!chatAvailable){chatAvailable=true;app.mainChat.reset();app.mainChat.handlePresence(user.nick,1);app.mainChat.getHistory();app.mainChat.showLoginLink();$('.chatConnectionStatus').hide();$('.chatMessageBox, .chatSendButton').attr('disabled',!chatAvailable);setTimeout("notifyChatAvailable.send();",0);}
if(presence.getFrom()==confs.chat.jid+'/'+confs.chat.nick&&type=='unavailable'){chatAvailable=false;app.mainChat.showLoginLink();if(app.main_auction.status!='closed'||app.main_auction.chatStatus!='closed'){$('.chatConnectionStatus').show();}
$('.chatMessageBox, .chatSendButton').attr('disabled',!chatAvailable);}else{var sender=getNickname(presence.getFrom());if(sender&&sender!=chatBot.name&&sender!=user.nick){if(!type&&!show){app.mainChat.handlePresence(sender,1);}else{app.mainChat.handlePresence(sender,0);}}}}}
function handleMessage(message){if(!resource){resource=message.getTo().substr(message.getTo().indexOf('/')+1);}
var from=message.getFrom();var body='';var children=message.getNode().getElementsByTagName('body').item(0).childNodes;for(var i=0;i<children.length;i++){body+=children[i].nodeValue;}
var data=JSJaCJSON.parse(body);oDbg.log("[Msg recv] from: "+from+", body: "+body,2);if(app.ticker){if(message.getFrom()==confs['ticker'].jid+'/'+bot.name){if(data.msg_id>confs['ticker'].msg_id){app.ticker.processSystemMessage(data);app.ticker.addMessage(data);}
return;}
if(data.ticker_history){app.ticker.loadHistory(data.ticker_history,data.first_index,data.request_last_index);}
if(data.system_history){app.ticker.loadSystemHistory(data.system_history);}}
if(!isPartnerPage){if(cutResource(message.getFrom())==cutResource(bot.jid)){setAuctionInfo(JSJaCJSON.parse(body));}
if(message.getFrom()==chatBot.jid){setChatInfo(JSJaCJSON.parse(body));}}
if(message.getFrom()==info_bot.jid){setAuctionsListInfo(JSJaCJSON.parse(body));}
if(message.getFrom()==confs['info'].jid+'/'+bot.name){if(data.msg_id>confs['info'].msg_id){updateAuctionInfo(data);}}
if(app.mainChat&&confs.chat&&cutResource(from)==confs.chat.jid){if(message.getNode().getElementsByTagName('x').length==0){if(message.getType()!='error'){var message=JSJaCJSON.parse(body);if(message.system){app.mainChat.handleSystemMessage(message);}else{app.mainChat.addMessage(message);}}}}}
function onConnect(){if(!isPartnerPage){getAuctionInfo();getChatsInfo();}else{getPartnerTickerInfo();}
setAuctionsListIds();}
function send(to,body,cb){try{var aMessage=new JSJaCMessage();aMessage.setTo(new JSJaCJID(to));aMessage.setBody(body);if(isConference(to)){aMessage.setType('groupchat');}
con.send(aMessage,cb);}catch(ex){oDbg.log("[sendMessage error: "+ex.toString(),1);}}
function sendMessage(body,cb){var send_=function(body,cb){send(bot.jid,body,cb);}
deferred(con,send_,connected,notifyConnected)(body,cb);}
function sendChatMessage(body,cb){var send_=function(body,cb){send(chatBot.jid,body,cb);}
deferred(con,send_,connected,notifyConnected)(body,cb);}
function sendInfoMessage(body,cb){var send_=function(body,cb){send(info_bot.jid,body,cb);}
deferred(con,send_,connected,notifyConnected)(body,cb);}
function isConference(jid){for(var i in confs){if(confs[i].jid==jid){return true;}}
return false;}
function enterToConference(conference){var aPresence=new JSJaCPresence();aPresence.setTo(conference.jid+"/"+conference.nick);con.send(aPresence);}
function quitFromConference(name){var aPresence=new JSJaCPresence();aPresence.setType('unavailable');aPresence.setTo(confs[name].jid+"/"+confs[name].nick);con.send(aPresence);}
function getAuctionInfo(){if(typeof app.main_auction=='undefined'||app.main_auction==null)
{return;}
var query={"auction":app.main_auction.id,"info":1};sendMessage(JSJaCJSON.toString(query));}
function getPartnerTickerInfo(){var query={"ticker_partners_info":1};sendMessage(JSJaCJSON.toString(query),function(message){setTickerInfo(JSJaCJSON.parse(message.getBody()));});}
function getChatsInfo(){var query={"info":1};sendChatMessage(JSJaCJSON.toString(query));}
function setAuctionsListIds(){var ids=[];for(var i in app.live_auctions){ids.push(i);}
for(i in app.upcoming_auctions){ids.push(i);}
for(i in app.partner_auctions){ids.push(i);}
var query={"ids":ids};sendInfoMessage(JSJaCJSON.toString(query));}
function cutResource(aJID){if(typeof(aJID)=='undefined'||!aJID)
return;var retval=aJID;if(retval.indexOf("/")!=-1)
retval=retval.substring(0,retval.indexOf("/"));return retval;}
function getNickname(aJID){if(typeof(aJID)=='undefined'||!aJID)
return;var start=aJID.indexOf('/')+1;var end=(aJID.indexOf('?')>0)?aJID.indexOf('?'):aJID.length;return aJID.substr(start,end-start);}
function setTickerInfo(info){if(info.conference&&app.ticker){confs['ticker']=info.conference;enterToConference(confs['ticker']);app.ticker.init();app.ticker.getHistory();}}
function setAuctionInfo(info){try{if(!info)return;if(info.start_time){app.main_auction.startTime=info.start_time;}
if(info.closing_time){app.main_auction.closeTime=info.closing_time;}
if(info.timer&&info.status&&info.status!='closed'){startCountdown('timer',info.timer,function(){window.setTimeout('app.main_auction.checkStatus()',5000);});}
if(info["pause reason"]){app.main_auction.pauseReason=info["pause reason"];}
if(info.status){app.main_auction.setStatus(info.status,info.timer);}
if(info.start_price){app.main_auction.setStartPrice(info);}
if(typeof info.proxy!='undefined'){app.main_auction.setProxy(info);}
if(info.bido_price){app.main_auction.bidoPrice=info.bido_price;}
if(info.bids){app.main_auction.addBids(info.bids);}
if(info.offer){app.main_auction.offerTimer=info.offer;app.main_auction.updateOffer();}
app.main_auction.update();if(info.conferences){confs['info']=info.conferences.info;enterToConference(confs['info']);if(app.ticker&&info.conferences.ticker){confs['ticker']=info.conferences.ticker;enterToConference(confs['ticker']);app.ticker.init();app.ticker.getHistory();}}
if(info.user_logged_out){if(confs.info&&confs.info.jid){$('#tab-content-chat').css('text-align','center');$('#tab-content-chat').html('<br />You must be logged in to view and participate in the chatroom.');}}}catch(ex){oDbg.log('[setAuctionInfo] error: '+ex.toString(),1);}}
function updateAuctionInfo(info){try{if(info.start_time){app.main_auction.startTime=info.start_time;}
if(info.closing_time){app.main_auction.closeTime=info.closing_time;}
if(info["pause reason"]){app.main_auction.pauseReason=info["pause reason"];}
if(info.status){app.main_auction.setStatus(info.status,info.timer);}
if(info.proxy){app.main_auction.userProxy=info.proxy;}
if(info.bido_price){app.main_auction.bidoPrice=info.bido_price;}
if(info.bids){app.main_auction.addBids(info.bids);app.main_auction.update(true);}
if(info.retracted){app.main_auction.setRetracted(info.retracted);}
if(info.offer){app.main_auction.offerTimer=info.offer;app.main_auction.updateOffer();}
if(info.current_price){app.main_auction.setPrice(info.current_price);}
if(info.emergency_enable){$('#emergency').text(info.emergency);$('#emergency').show();}
if(info.emergency_disable){$('#emergency').hide();}
app.main_auction.update();if(info.timer&&info.status&&info.status!='closed'){startCountdown('timer',info.timer,function(){window.setTimeout('app.main_auction.checkStatus()',5000);});}
if(info.chat_opened){app.mainChat['jid']=chats[app.main_auction.id]['jid']=info.jid;app.mainChat['nick']=chats[app.main_auction.id]['nick']=confs['info']['nick'];app.main_auction.setChatStatus('opened');}
if(info.chat_closed){app.main_auction.setChatStatus('closed');}
if(getShortAuction(app.main_auction.id)){var params={};params[app.main_auction.id]={'current_price':app.main_auction.price,'high_bidder':app.main_auction.highBidderId,'status':app.main_auction.status,'proxy':app.main_auction.userProxy,'bido_price':app.main_auction.bidoPrice,'start_time':app.main_auction.startTime,'closing_time':app.main_auction.closeTime}
if(info.bids){params[app.main_auction.id]['bids']=info.bids;}
if(info.timer){params[app.main_auction.id]['timer']=info.timer;}
setAuctionsListInfo(params);}}catch(ex){oDbg.log('[updateAuctionInfo] error: '+ex.toString(),1);}}
function setChatInfo(info){try{if(info.chats){for(var i in info.chats){chats[i]=info.chats[i];}
if(!app.main_auction.locationHome&&typeof(chats[app.main_auction.id])=='undefined'){chats[app.main_auction.id]={'auction_name':app.main_auction.name.toLowerCase()};}
if(app.mainChat&&(chats[app.main_auction.id])&&!(app.mainChat.parentId=='lobby')){confs['chat']=chats[app.main_auction.id];app.mainChat.parentId=app.main_auction.id;}else{confs['chat']=chats['lobby'];app.mainChat.parentId='lobby';}
if(confs['chat'].logged){enterToConference(confs['chat']);$('.chatConnectionStatus').hide();}
$('.chatConnectionStatus').html(auctionTexts.lobbyOpened);updateChatList();if(app.mainChat&&app.main_auction.status=='closed'){app.mainChat.getHistory();}}
if(app.mainChat&&info.history){app.mainChat.loadHistory(info.history,info.first_index,info.request_last_index);}}catch(ex){oDbg.log('[setChatInfo] error: '+ex.toString(),1);}}
function updateChatInfo(info){try{if(info.chat_list){chats={};for(var i in info.chat_list){chats[i]=info.chat_list[i];}
if(!app.main_auction.locationHome&&typeof(chats[app.main_auction.id])=='undefined'){chats[app.main_auction.id]={'auction_name':app.main_auction.name.toLowerCase()};}
updateChatList();}}catch(ex){oDbg.log('[updateChatInfo] error: '+ex.toString(),1);}}
function switchChat(select){try{if(select.value=='lobby'||(select.value==app.main_auction.id&&!app.main_auction.locationHome)){quitFromConference('chat');app.mainChat.reset();confs.chat=chats[select.value];app.mainChat.parentId=select.value;if(select.value=='lobby'||app.main_auction.chatStatus=='opened'){if(chatAvailable){chatAvailable=false;enterToConference(confs.chat);}else{$('.chatConnectionStatus').css('text-align','center');$('.chatConnectionStatus').html(auctionTexts.chatOpened);$('.chatConnectionStatus').show();if($('#chatEnterLink').text()==auctionTexts.chatroomClosed||$('#chatEnterLink').html()==auctionTexts.loginLobby){app.mainChat.showLoginLink();}}
$('.chatMessageBox, .chatSendButton').attr('disabled',!chatAvailable);}else if(app.main_auction.status=='not started'){app.main_auction.chatStatus='closed';$('.chatConnectionStatus').css('text-align','left');$('.chatConnectionStatus').html(auctionTexts.chatNotOpened);$('.chatConnectionStatus').show();$('#chatEnterLink').html('<a href="javascript:void(0)" onclick="loginToLobby()">Login to lobby</a>');$('.chatMessageBox, .chatSendButton').attr('disabled',true);}else{app.mainChat.getHistory();$('.chatConnectionStatus').hide();$('#chatEnterLink').html(auctionTexts.chatroomClosed);$('.chatMessageBox, .chatSendButton').attr('disabled',true);}}else if(select.value!=confs.chat.id){$.cookie("chat",1);var url='/Auction?name='+encodeURIComponent(chats[select.value].auction_name);if(chats[select.value].sale_number>1){url+='&n='+chats[select.value].sale_number;}
document.location=url;}}catch(ex){oDbg.log('[switchChat] error: '+ex.toString(),1);}}
function loginToLobby(){$('.chatSelect').val('lobby');switchChat($('.chatSelect')[0]);app.mainChat.login();}
function updateChatList(){var chatSelectObject=$('#chatList .chatSelect');var selectedId=chatSelectObject.val()||(!app.main_auction.locationHome&&app.main_auction.id)||'lobby';chatSelectObject.find('option').remove();$(sortChats()).each(function(i,val){var chat_name=val.auction_name||'Lobby';chat_name+=(app.mainChat.parentId!=val.id&&val.auction_est_time?', '+secondsToTime(val.auction_est_time):'');if(chatAvailable&&app.mainChat.parentId==val.id){var users_count=app.mainChat.getUsersCount();}else{var users_count=val.users_count+1;}
chat_name+=' ('+(users_count||0)+')';$('<option>').attr('value',val.id).text(chat_name).appendTo(chatSelectObject);});$('option[value=lobby]',chatSelectObject).prependTo(chatSelectObject);chatSelectObject.val(selectedId).unbind('change').change(function(){switchChat(this);});}
function sortChats(){var sorted=[];for(var i in chats){if(chats[i].adult==1&&app.ticker&&app.ticker.settings['adult']=='0'){continue;}
var chat=chats[i];chat.id=i;sorted.push(chat);}
return sorted.sort(function(a,b){return a.auction_name>b.auction_name});}
function setAuctionsListInfo(info){try{for(var i in info){var auction=getShortAuction(i);if(auction){if(info[i].start_time){auction.startTime=info[i].start_time;}
if(info[i].closing_time){auction.closeTime=info[i].closing_time;}
if(info[i].bido_price){auction.bidoPrice=info[i].bido_price;}
if(info[i].current_price){auction.setPrice(info[i].current_price);}
if(info[i].high_bidder){auction.highBidderId=info[i].high_bidder;}
if(info[i].status){auction.setStatus(info[i].status);}
if(info[i].timer&&auction.status!='closed'){startCountdown('timer_'+auction.id,info[i].timer,null,6);startCountdown('block_timer_'+auction.id,info[i].timer);if($('#bidWindowAuctionId').val()==auction.id){startCountdown('block_timer_place_bid_'+auction.id,info[i].timer);}}
if(info[i].proxy){auction.userProxy=info[i].proxy;}
if(info[i].bids){auction.addBids(info[i].bids);}
if(info[i].bids_amount){auction.bidsCount=info[i].bids_amount;}
if(typeof(info[i].high_bidder)!='undefined'){var element=$('#upcoming_row_'+i+' .place_bid');if(info[i].high_bidder){element.addClass('high-bid');}else{if(element.hasClass('high-bid')){element.removeClass('high-bid');element.addClass('has-bid');}}}
if(info[i].retracted){auction.setRetracted(info[i].retracted);}
if(info[i].views_count){auction.recalcGaugeCode('views',info[i].views_count);}
auction.update();}}}catch(ex){oDbg.log('[updateShortAuctionInfo] error: '+ex.toString(),1);}}
function Notification(){this.listeners=[];this.addListener=function(listener,singleCall){var i=this.findListener(listener);if(-1===i)this.listeners.push([listener,singleCall]);}
this.removeListener=function(listener){var i=this.findListener(listener);if(-1!==i){delete this.listeners[i];this.listeners.splice(i,1);}}
this.findListener=function(listener){for(var i=0;i<this.listeners.length;i++){if(this.listeners[i]&&listener===this.listeners[i][0]){return i;}}
return-1;}
this.clearListeners=function(){while(this.listeners.length){this.listeners.pop();}}
this.send=function(sender){for(var i=0;i<this.listeners.length;i++){var listener=this.listeners[i][0];var doRemove=(this.listeners[i][1])?true:false;listener.apply(null,arguments);if(doRemove){this.removeListener(listener);i--;}}}
this.toString=function(){return'[Notification]';}
return this;}
function deferred(object,fn,check,notification){return function(){if(check){fn.apply(object,arguments);return true;}else{var args=[];for(var i=0;i<arguments.length;i++){args.push(arguments[i]);}
notification.addListener(function(){fn.apply(object,args);delete args;},true);}
return false;}}

function storeCaret(element){if(document.selection&&document.selection.createRange){element.caretPos=document.selection.createRange().duplicate();}}
function Chat(){this.parentId;this.msgBoard;this.msgBox;this.users={};this.messages={};this.scroll=true;this.lockAutoScroll=false;this.welcomeMessage={body:'',message_id:'welcome_message'};this.showWelcomeMessage=false;this.systemMessenger='System';this.soundEnabled=false;this.soundDelay=500;this.soundTimerId;this.historyFirstIndex=0;this.historyRequestLastIndex=-1;this.init=function(){this.msgBoard=$('.chatMessages');this.msgBoard.bind('scroll',this.onScroll);this.msgBox=$('.chatMessageBox');this.toggleSound(false);}
this.sendMessage=function(){var message=this.msgBox.val();if(message.length==0){return false;}
if($('#isSystemMessage').length&&$('#isSystemMessage')[0].checked){sendChatMessage(JSJaCJSON.toString({'chat':this.parentId,'sys_msg':message}));}else{sendChatMessage(JSJaCJSON.toString({'chat':this.parentId,'message':message}));}
this.msgBox.val('');return false;}
this.addMessage=function(data,toTop,rawHTML){var rawHTML=rawHTML||false;var toTop=toTop||false;if(this.messages[data.message_id]){return;}
this.messages[data.message_id]=data;var theDate=new Date(data.time*1000);var time=formatNumber(theDate.getHours())+':'+formatNumber(theDate.getMinutes());var nick=data.nick;var html='<div class="'+this.getMessageClass(nick)+'">';if(nick){html+='<span class="messageTime">['+time+']</span> ';html+='<span class="messageNick" onClick="app.mainChat.addNickname(\''+nick+'\')">'+nick+': </span>';}
var messageText=(rawHTML?this.makeTags(data.body):this.makeTags(escapeHTML(data.body)));html+='<span>'+messageText+'</span></div>';this.lockAutoScroll=true;if(toTop){this.msgBoard.find('#moreLink').after(html);}else{this.msgBoard.append(html);}
this.scrollDown();this.lockAutoScroll=false;if(nick!=user.nick){this.playSound();}}
this.getMessageClass=function(nick){var style='messageBody';if(nick==user.nick){style+='User';}else if(!nick||nick==this.systemMessenger){style+='System';}
return style;}
this.onScroll=callback(this,function(){if(!this.lockAutoScroll){this.scroll=(($.browser.opera?17:0)+this.msgBoard.attr('scrollTop')+this.msgBoard.attr('clientHeight')>=this.msgBoard.attr('scrollHeight'));}})
this.scrollDown=function(){if(this.scroll){this.msgBoard.scrollTop(this.msgBoard.attr('scrollHeight')-this.msgBoard.attr('clientHeight'));}}
this.scrollToBottom=function(){this.msgBoard.scrollTop(this.msgBoard.attr('scrollHeight')-this.msgBoard.attr('clientHeight'));}
this.handlePresence=function(userNick,presence){if(this.getUsersCount()==0){var div=$('<div class="chatUser chatUserBido" onclick="app.mainChat.addNickname(\''+this.systemMessenger+'\')">'+this.systemMessenger+'</div>');$('.chatUsers').append(div);this.users[this.systemMessenger]={'body':div[0],'counter':1};}
if(presence){if(this.users[userNick]){this.users[userNick].counter=this.users[userNick].counter+1;}else{var div=$('<div class="chatUser" onClick="app.mainChat.addNickname(\''+userNick+'\')">'+userNick+'</div>');$('.chatUsers').append(div);this.users[userNick]={'body':div[0],'counter':1};}}else{if(this.users[userNick]){if(this.users[userNick].counter>1){this.users[userNick].counter=this.users[userNick].counter-1;}else{$(this.users[userNick].body).remove();delete this.users[userNick];}}}
this.updateUsersCount();}
this.getUsersCount=function(){var sum=0;for(var i in this.users){sum=sum+1;}
return sum;}
this.getMessagesCount=function(){var sum=0;for(var i in this.messages){sum=sum+1;}
return sum;}
this.addNickname=function(user){var message=this.msgBox[0];if(!message.caretPos&&document.selection&&document.selection.createRange){message.focus();}
if(message.caretPos&&!$.browser.opera){message.caretPos.moveStart('character',-message.value.length);message.caretPos.text='@'+user+' '+message.caretPos.text;message.caretPos.select();}else{message.value='@'+user+' '+message.value;message.focus();}}
this.handleSystemMessage=function(message){if(message.reason&&message.reason=='hold'&&message.nickname==user.nick){document.location.reload();return;}
if(message.penalty&&message.nickname==user.nick){this.showPenaltyMessage(message);}
if(message.body){this.addMessage(this.systemMessenger,message.body);}
if(message.system==2){if(message.chats_list){for(var i in chats){if(typeof(message.chats_list[i])=='undefined'){delete chats[i];}}
for(var i in message.chats_list){if(typeof(chats[i])=='undefined'){chats[i]=message.chats_list[i];chats[i].nick=confs.chat.nick;}else{for(var j in message.chats_list[i]){chats[i][j]=message.chats_list[i][j];}}}
if(!app.main_auction.locationHome&&typeof(chats[app.main_auction.id])=='undefined'){chats[app.main_auction.id]={'auction_name':app.main_auction.name.toLowerCase()};}}
updateChatList();}}
this.showPenaltyMessage=function(message){$('#chatToolbar').hide();$('#chatInfoBox').html(message.reason);$('#chatInfoBox').show();$('.chatMessageBox, .chatSendButton, .chatSelect').attr('disabled',1);window.setTimeout(this.hidePenaltyMessage,message.penalty*1000);}
this.hidePenaltyMessage=function(){$('#chatToolbar').show();$('#chatInfoBox').hide();$('.chatMessageBox, .chatSendButton, .chatSelect').attr('disabled',0);}
this.setStyle=function(type){var message=this.msgBox[0];var open='['+type.substr(0,1)+']';var close='[/'+type.substr(0,1)+']';if(!message.disabled){if(message.caretPos){message.caretPos.text=open+message.caretPos.text+close;message.caretPos.move('character',-close.length);message.caretPos.select();if($.browser.opera){message.setSelectionRange(message.selectionStart,message.selectionStart);}}else if(message.selectionStart+1&&message.selectionEnd+1){var text=message.value;var start=message.selectionStart;var end=message.selectionEnd;message.value=text.substr(0,start)+open+text.substr(start,end-start)+close+text.substr(end);message.setSelectionRange(open.length+end,open.length+end);}else{message.value+=open+close;if(message.setSelectionRange){message.setSelectionRange(message.value.length-close.length,message.value.length-close.length);}}
message.focus();}}
this.switchButton=function(type,on){if(on){$('#chat_'+type+'_on').css('display','');$('#chat_'+type+'_off').css('display','none');}else{$('#chat_'+type+'_on').css('display','none');$('#chat_'+type+'_off').css('display','');}}
this.makeTags=function(text){if(typeof(text)=='undefined')
return'';text=text.toString();var find=Array("[b]","[/b]","[i]","[/i]","[u]","[/u]","[s]","[/s]");for(var i=0;i<find.length;i+=2){var lowerText=text.toLowerCase();var lastOpenPos=lowerText.lastIndexOf(find[i]);if(lastOpenPos>=0&&lastOpenPos>lowerText.lastIndexOf(find[i+1])){text+=find[i+1];}}
text=text.replace(/\[b\]/ig,"<b>");text=text.replace(/\[\/b\]/ig,"</b>");text=text.replace(/\[i\]/ig,"<i>");text=text.replace(/\[\/i\]/ig,"</i>");text=text.replace(/\[u\]/ig,"<u>");text=text.replace(/\[\/u\]/ig,"</u>");text=text.replace(/\[s\]/ig,"<s>");text=text.replace(/\[\/s\]/ig,"</s>");return text;}
this.getHistory=function(){var query={'chat':this.parentId,'history':1,'first_index':this.historyFirstIndex,'count':this.getMessagesCount()?500:20};sendChatMessage(JSJaCJSON.toString(query));}
this.loadHistory=function(history,first_index,request_last_index){if(request_last_index==this.historyRequestLastIndex){return false;}
this.historyRequestLastIndex=request_last_index;this.historyFirstIndex=first_index;if(first_index>0){if(first_index==1){var linkText='View previous 1 message';}else{var linkText='View previous '+Math.min(first_index,500)+' messages';}
$('#moreLink a').text(linkText);$('#moreLink').show();}else{$('#moreLink').hide();}
var toTop=this.getMessagesCount()?1:0;if(toTop){history.reverse();}
for(var i in history){this.addMessage(history[i],toTop);}
if(!this.loaded){if(this.welcomeMessage.body&&this.showWelcomeMessage){this.addMessage(this.welcomeMessage,true,true);}else{this.addMessage({body:'Welcome back!',message_id:'welcome_message'},true);}
this.loaded=true;this.showWelcomeMessage=false;}}
this.show=function(){this.showLoginLink();this.scrollDown();}
this.showLoginLink=function(){if($('#tab-content-chat').css('display')=='block'){var text='';if(chatAvailable){text='<a href="javascript:void(0)" onclick="app.mainChat.logout()">Log out of chat</a>';}else{text=auctionTexts.loginLobby;}
$('#chatEnterLink').html(text);}}
this.reset=function(){this.clear();this.clearUsers();}
this.login=function(){enterToConference(confs['chat']);sendChatMessage(JSJaCJSON.toString({'login':1}));}
this.logout=function(){quitFromConference('chat');sendChatMessage(JSJaCJSON.toString({'logout':1}));this.deleteUser(app.main_auction.userNick);this.updateUsersCount();this.clear();this.clearUsers();}
this.clear=function(){var children=this.msgBoard.children();for(var i=0;i<children.length;i++){if(children[i]){if(children[i].id!='moreLink'){$(children[i]).remove();}}}
$('#moreLink').hide();this.messages={};this.historyFirstIndex=0;this.historyRequestLastIndex=-1;}
this.deleteUser=function(nick){if(typeof(this.users[nick])!='undefined'){$(this.users[nick].body).remove();delete this.users[nick];}}
this.clearUsers=function(){for(var i in this.users){$(this.users[i].body).remove();delete this.users[i];}}
this.toggleSound=function(enable){this.soundEnabled=enable;if(enable){$('#chat_sound_on').show();$('#chat_sound_off').hide();}else{$('#chat_sound_on').hide();$('#chat_sound_off').show();}}
this.playSound=function(){if(this.soundEnabled){window.clearTimeout(this.soundTimerId);this.soundTimerId=window.setTimeout('playSound("msg_recv")',this.soundDelay);}}
this.updateUsersCount=function(){if(chatAvailable){var chat=chats[$('.chatSelect>option:selected').val()];var name=chat.auction_name?chat.auction_name:'Lobby';$('.chatSelect>option:selected').text(name+' ('+(app.mainChat.getUsersCount())+')');}}}

function Ticker(){this.msgBoard;this.msgBox;this.scroll=true;this.lockAutoScroll=false;this.messages={};this.welcomeMessage=null;this.settings={'adult':0}
this.guest=false;this.guestSettings={}
this.guestColors={}
this.historyFirstIndex=0;this.historyRequestLastIndex=-1;this.historyLoaded=false;this.messagesPerPage=100;this.messagesFirstPage=20;this.type='public';this.init=function(){this.msgBoard=$('.tickerMessages');this.msgBoard.bind('scroll',this.onScroll);this.msgBox=$('.tickerMessageBox');this.msgPauseButton=$('.tickerPause');if(this.type=='partner'){this.messagesPerPage=500;}}
this.addMessage=function(data,toTop){if(this.messages[data.msg_id]){return;}
if(this.guest){if(typeof(this.guestSettings[data.name])=='undefined'){if(data.type!=0){return;}}
if(typeof(this.guestColors[data.type])!='undefined'){data.color=this.guestColors[data.type];}}else{if(typeof(this.settings[data.type])=='undefined'){return;}
if(this.settings[data.type].enabled!='1'){return;}}
if(data.adult&&this.settings['adult']!='1'){return;}
if(data.color){var color=data.color;}else{var color=this.settings[data.type].color;}
this.messages[data.msg_id]=data;var theDate=new Date(data.time*1000);var time;if(this.type=='partner'){var weekday=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];time=weekday[theDate.getDay()]+', '+formatNumber(theDate.getHours())+':'+formatNumber(theDate.getMinutes());}else{time=formatNumber(theDate.getHours())+':'+formatNumber(theDate.getMinutes());}
var html='<div class="msg"><span class="messageTime">['+time+']</span> ';html+='<span class="messageText messageType'+data.type+'" style="color: '+color+';">'+data.body+'</span></div>';this.lockAutoScroll=true;if(toTop){this.msgBoard.find('#tickerMoreLink').after(html);}else{this.msgBoard.append(html);}
this.scrollDown();this.lockAutoScroll=false;}
this.pause=function(){if(this.scroll){this.scroll=false;}else{this.scrollToBottom();this.scroll=true;}
this.updatePauseButton();}
this.updatePauseButton=function(){this.msgPauseButton.attr('src','/images/buttons/pause'+(this.scroll?'':'-pressed')+'.png');}
this.onScroll=callback(this,function(){if(!this.lockAutoScroll){this.scroll=(($.browser.opera?17:0)+this.msgBoard.attr('scrollTop')+this.msgBoard.attr('clientHeight')>=this.msgBoard.attr('scrollHeight'));this.updatePauseButton();}})
this.scrollDown=function(){if(this.scroll){this.msgBoard.scrollTop(this.msgBoard.attr('scrollHeight')-this.msgBoard.attr('clientHeight'));}}
this.scrollToBottom=function(){this.msgBoard.scrollTop(this.msgBoard.attr('scrollHeight')-this.msgBoard.attr('clientHeight'));}
this.getMessagesCount=function(){var sum=0;for(var i in this.messages){sum=sum+1;}
return sum;}
this.getHistory=function(){var ignore=[];for(var i in app.ticker.settings){if(app.ticker.settings[i].enabled==0){ignore.push(parseInt(i));}}
var query={'first_index':this.historyFirstIndex,'count':this.historyLoaded?this.messagesPerPage:this.messagesFirstPage,'ignore':ignore};if(this.type=='partner'){query.ticker_partners_history=1;}else{query.ticker_history=1;}
if(this.guest){query['guest']=1;}
sendMessage(JSJaCJSON.toString(query));}
this.loadHistory=function(history,first_index,request_last_index){$('.tickerConnectionStatus').hide();if(request_last_index==this.historyRequestLastIndex){return false;}
this.historyRequestLastIndex=request_last_index;this.historyFirstIndex=first_index;if(first_index>0){if(first_index==1){var linkText='View previous 1 message';}else{var linkText='View previous '+Math.min(first_index,this.messagesPerPage)+' messages';}
$('#tickerMoreLink a').text(linkText);$('#tickerMoreLink').show();}else{$('#tickerMoreLink').hide();}
var toTop=this.getMessagesCount()?1:0;if(history.length&&toTop){history.reverse();}
for(var i in history){this.addMessage(history[i],toTop);}
if(!this.historyLoaded){this.showWelcomeMessage();this.historyLoaded=true;}}
this.loadSystemHistory=function(history){var processed=[];for(var i in history.reverse()){var info=JSJaCJSON.parse(history[i].body);if($.inArray(info.id,processed)==-1){processed.push(info.id);this.processSystemMessage(history[i]);}}}
this.showWelcomeMessage=function(){if(this.welcomeMessage){var welcomeMsg=$('<div />').attr('id','tickerWelcomeMessage').html(this.welcomeMessage);this.msgBoard.append(welcomeMsg);}}
this.removeMessages=function(){this.msgBoard.find('.msg').hide('slow');}
this.removeHistoryLink=function(){$('#tickerMoreLink').hide('slow');}
this.processSystemMessage=function(data){if(data.type==95){this.removeMessages();this.removeHistoryLink();}
if(typeof(app.tabs)=='undefined'){return false;}
if(data.adult&&this.settings['adult']!='1'){return false;}
if(data.type==96){var info=JSJaCJSON.parse(data.body);app.tabs.upcoming.newRow(info);}
if(data.type==97){var info=JSJaCJSON.parse(data.body);app.tabs.submitted.updateVotesCount(info.id,info.votes_count,info);setDomainHot(info.id,info.hot);}
if(data.type==98){var info=JSJaCJSON.parse(data.body);app.tabs.upcoming.removeRow(info.id);app.tabs.live.newRow(info);}
if(data.type==99){var info=JSJaCJSON.parse(data.body);app.tabs.live.removeRow(info.id);app.tabs.upcoming.removeRow(info.id);app.tabs.past.newRow(info);}}}

$(document).ready(function(){$(document.body).append('<div id="soundContainer" style="position: absolute; left: -2000px; z-index: -1;"></div>');});var SOUNDS={'msg_recv':'media/msg.swf','outbid':'media/outbid.swf','win':'media/win.swf'}
function playSound(action){var sound=SOUNDS[action];if($.browser.msie){document.getElementById('soundContainer').innerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0"><param name="movie" value="'+sound+'"><param name="quality" value="high"><param name="loop" value="false"></object>';}else{$('#soundContainer').html('<embed src="'+sound+'" width="1" height="1" loop="false" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash"></embed>');}}
var colors;var colorId=0;var timerId=null;var colorElement=null;var highColors=new Array("00AA00","02be02","02d102","02e402","02f602","02f602","02e402","02d102","02be02","00AA00","019901","018a01","018001","018001","018a01","019901","00AA00");var outColors=new Array("AA0000","c00202","e11313","fb2b2b","fb2b2b","e11313","c00202","AA0000","9a0101","780000","780000","9a0101","AA0000");function playColor(type,duration,el){colors=(type=='high')?highColors:outColors;var stopEffect=function(){timerId=null;}
colorElement=el;timerId=window.setTimeout(stopEffect,duration);playEffect();}
function playEffect(){if(timerId||colorId!=colors.length-1){if(colorElement)
colorElement.css('color',"#"+getNextColor());window.setTimeout("playEffect()",50);}}
function getNextColor(){colorId++;if(colorId>=colors.length)
colorId=0;return colors[colorId];}

var _timer={};var month=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];var COUNTDOWN_STEP=5;function startCountdown(id,time,func,timeFormat,paused,strFormat){if(!_timer[id]){_timer[id]={'time':parseInt(time),'func':func,'timeFormat':timeFormat,'pause':paused,'timerId':null,'show':true,'strFormat':strFormat};updateCountdown(id);}else{setCountdownTimer(id,time);}}
function updateCountdown(id){if(!_timer[id]){return false;}
var time=_timer[id]['time'];var str='';var date=new Date(time*1000);var utcDate=new Date(date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate(),date.getUTCHours(),date.getUTCMinutes(),date.getUTCSeconds());if(id=='clock'){str=utcDate.format('yyyy mmm dd hh:MM:ss TT');_timer[id]['time']=_timer[id]['time']+COUNTDOWN_STEP;}else if(id.substr(id.length-5)=='Watch'){str=utcDate.format(_timer[id]['strFormat']);_timer[id]['time']=_timer[id]['time']+COUNTDOWN_STEP;;}else{if(time<=0){$('#'+id).html('Closed');if(typeof _timer[id].func=='function'){_timer[id].func();}
return;}
str=getCountdownTime(time,_timer[id]['timeFormat'],_timer[id]['strFormat']);if(_timer[id]['pause']){if(!_timer[id]['show']){str='&nbsp;';}
_timer[id]['show']=!_timer[id]['show'];}else{_timer[id]['time']=_timer[id]['time']-COUNTDOWN_STEP;}}
$('#'+id).html(str);_timer[id].timerId=setTimeout("updateCountdown('"+id+"')",COUNTDOWN_STEP*1000);}
function pauseCountdown(id,pause){if(_timer[id]){_timer[id]['pause']=pause;}}
function stopCountdown(id,hide){if(_timer[id]){delete _timer[id];if(hide){$('#'+id).html('&nbsp;');}}}
function getCountdownTime(time,timeFormat,strFormat){time=time+59;var unixTime=time;var days=Math.floor(time/86400);time=time%86400;var hours=Math.floor(time/3600);time=time%3600;var mins=Math.floor(time/60);time=time%60;var sec=time;var str='';if(!timeFormat){if(days==0&&hours==0&&mins==1){str='Less than one minute';}else{if(days>0){str=days+' day'+((days==1)?'':'s')+' '+formatNumber(hours)+' hour'+((hours==1)?'':'s')+' '+formatNumber(mins)+' min'+((mins==1)?'':'s');}else{str=formatNumber(hours)+' hour'+((hours==1)?'':'s')+' '+formatNumber(mins)+' min'+((mins==1)?'':'s');}}}
if(timeFormat==1){if(days==0){str=formatNumber(hours)+' hour'+((hours==1)?'':'s')+' '+formatNumber(mins)+' min'+((mins==1)?'':'s');}else{str=days+' day'+((days==1)?' ':'s ')+formatNumber(hours)+'h '+formatNumber(mins)+'m';}}
if(timeFormat==2){if(days==0){str=formatNumber(hours)+'h'+' : '+formatNumber(mins)+'m';}else{str=days+' day'+((days==1)?' ':'s ')+formatNumber(hours)+' : '+formatNumber(mins);}}
if(timeFormat==3){if(days==0){str=formatNumber(hours)+' : '+formatNumber(mins);}else{str=days+'d '+formatNumber(hours)+':'+formatNumber(mins);}}
if(timeFormat==4){if(days==0){str=formatNumber(hours)+':'+formatNumber(mins);}else{str=days+'d '+formatNumber(hours)+':'+formatNumber(mins);}}
if(timeFormat==5){str=formatNumber(mins-1)+':'+formatNumber(sec);}
if(timeFormat==6){if(days==0&&hours==0&&mins==1){str='< 1m';}else{if(days>0){str=days+'d '+hours+'h '+mins+'m';}else if(hours>0){str=hours+'h '+mins+'m ';}else{str=mins+'m';}}}
if(timeFormat==7){if(days==0){str=formatNumber(hours)+':'+formatNumber(mins);}else{str=days+' day'+((days==1)?' ':'s ')+formatNumber(hours)+':'+formatNumber(mins);}}
if(timeFormat==8){str=(new Date(unixTime)).format(strFormat);}
return str;}
function setCountdownTimer(id,time){_timer[id]['time']=parseInt(time);window.clearTimeout(_timer[id].timerId);updateCountdown(id);}
function formatNumber(number){return(number<10)?"0"+number:number;}

function ShortAuction(){var auction=new Auction();auction.messageDelay=10000;auction.setStatus=function(status){if(status=='closed'&&(this.status=='opened'||this.status=='extended'||this.status=='not started')){this.closeAuction();}
if(status=='deleted'&&this.status!='deleted'){app.tabs.live.removeRow(this.id);}
if(status=='opened'){this.openAuction();}
if(status=='paused'){this.status=status;this.pause(true);}}
auction.closeAuction=function(){this.status='closed';app.tabs.live.removeRow(this.id);app.tabs.upcoming.removeRow(this.id);stopCountdown('timer_'+this.id,false);stopCountdown('block_timer_'+this.id,false);stopCountdown('block_timer_place_bid_'+this.id,false);$('#timer_'+this.id).text('Closed');$('.bidButton_'+this.id).hide();$('#bin_price_'+this.id+' a').parent().hide();$('#bid_'+this.id+', #upcoming_row_'+this.id+' .place_bid').removeClass("has-bid high-bid");if($('#bidWindowAuctionId').val()==this.id){$('#block_timer_place_bid_'+this.id).html('Closed');}
var block=this.getBlock();if(!block.length){return;}
var left=block.find('.ablock_header .left img')[0];if(left){if(this.bids.length()>0&&this.bidoPrice!='hidden'&&this.price>=this.bidoPrice){left.src=imagePath+'/images/soldAuction.png';}else{left.src=imagePath+'/images/closedAuction.png';}
left.alt='Closed Auction';left.title='Closed Auction';}
block.find('.auctionTitle').html('Closed auction: ');var children=block.find('.bid-block').children();for(var i=0;i<children.length;i++){var child=children[i];if(child.className!='bid_status_text'&&child.className!='ablock_header'&&child.className!='bidStatus'&&child.className!='ablock_info'&&child.className!='ablock_history'&&child.className!='visitor_link'){$(children[i]).remove();}}
block.find('.ablockInitBid').html('Closing price:');if(this.price==0){block.find('.currentBid').html('No bids');}
block.find('.ablockStartBid').remove();block.find('.ablockCurrentBid').remove();block.find('.currentBidAd').remove();if(this.bids.length()>0&&this.bidoPrice!='hidden'&&this.price>this.bidoPrice){var bid=this.bids.getLastNonRetracted();block.find('.ablock_info').append('<tr><td style="width: 100px;"><span style="font-size:12px;">Winner:</span></td><td>'+
(this.userNick=='visitor'?'<strong>'+bid.nick+'</strong>':'<a href="'+httpUrl+'/Profile/'+bid.nick+'">'+bid.nick+'</a>')
+'</td></tr>');}
if(this.startTime){var startTime=new Date(this.startTime*1000);block.find(".ablock_info").append('<tr><td style="width: 100px;"><span style="margin-top: 7px;">Start date:</span></td>'+'<td nowrap><span>'+startTime.format("mmm dd yyyy, hh:MM tt")+'</span></td></tr>');}
if(this.closeTime){var closeTime=new Date(this.closeTime*1000);block.find(".ablock_info").append('<tr><td style="width: 100px;"><span style="margin-top: 7px;">Close date:</span></td>'+'<td nowrap><span>'+closeTime.format("mmm dd yyyy, hh:MM tt")+'</span></td></tr>');}
if(this.userNick=='visitor'){block.find('.live_visitor_link').remove();block.find('.bidHistoryLink').show();}
if(this.buyItNowPrice){block.find('.buyNow').hide();}}
auction.openAuction=function(){if(this.status=='not started'){this.status='opened';var block=this.getBlock();var left=block.find('.ablock_header .left img')[0];if(left){left.src=imagePath+'/images/atAuction.png';left.alt='At Auction';left.title='At Auction';}
block.find('.ablockInitBid').html('Current bid:');if(this.price==0){block.find('.currentBid').html('No bids yet');}
if($('#binWindow').data('id')==this.id){$('#binWindow').hide();}
block.find('.auctionTitle').html('Live auction: ');block.find('.ablockStartBid').show();block.find('.ablockCurrentBid').show();block.find('.ablockReserve').show();block.find('.ablockTimerDate').hide();block.find('.ablockTimerTitle').html('Estimated time for Auction to end:');block.find('.pauseAuction').show();block.find('.guarantee_price').show();block.find('.cashback').hide();block.find('.userProxyHelp').html('(<a href="javascript:void(0)">?</a>)')
block.find('.userProxyHelp a').unbind().mouseover(function(){showHelpProcess(helpTexts.maxBid,this)}).click(function(){showHelpProcess(helpTexts.maxBid,this)});block.find('.userProxyHelp').show();if(this.userNick!='visitor'){block.find('.bidHistoryLink').show();}}
if(this.status=='paused'){this.status='opened';this.pause(false);}}
auction.update=function(eff){this.nextBid=this.getNextBid();var nextBid=this.nextBid.toString();var reg=/(\d+)(\d{3})/;while(reg.test(nextBid)){nextBid=nextBid.replace(reg,"$1,$2");}
$('#nextBid_'+this.id).text(nextBid);if(this.status=='paused'){this.pause(true);return;}
if(this.price){$('#price_'+this.id).text('$'+formatBidPrice(this.price,this.priceFormat));$('#high_bidder_'+this.id).text(this.highBidder);}else{$('#price_'+this.id).text('0');$('#high_bidder_'+this.id).text('none');}
$('#current_bid_window_'+this.id).text(this.price?'US $'+formatBidPrice(this.price,this.priceFormat):'No bids yet');if(this.bidsCount){$('#bids_count_'+this.id).text(this.bidsCount).attr('style','');$('#bids_count_text_'+this.id).text('bid'+(this.bidsCount==1?'':'s'));$('#bids_count_'+this.id).parent().show();this.recalcGaugeCode('bidding',this.bidsCount);}
if(this.userId&&this.highBidderId==this.userId){if(!this.userWinning){this.userWinning=true;if(eff){playColor('high',5000,$('#price_'+this.id));}}}else{if(this.userWinning){this.userWinning=false;if(eff){playColor('out',5000,$('#price_'+this.id));}}}
$('#price_'+this.id).css('color',this.getPriceColor());if(this.status!='closed'){$('#bid_'+this.id).removeClass("has-no-bid has-bid high-bid");if(this.userWinning&&(this.userBid>=this.bidoPrice||this.userProxy>=this.bidoPrice||this.bidoPrice=='hidden')){$('#bid_'+this.id).addClass('high-bid');}else{if((this.userBid||this.userProxy)&&this.status!='not started'){$('#bid_'+this.id).addClass('has-bid');}else{$('#bid_'+this.id).addClass('has-no-bid');}}}
if(bidHistory.auction.id==this.id&&bidHistory.isVisible()){bidHistory.update();}
if(this.guaranteePrice>0&&this.price>=this.guaranteePrice){$('#bidButton_'+this.id+'>div').show()}
if($('#bidWindowAuctionId').val()==this.id){$('#proxy_'+this.id).text('US $'+formatBidPrice(this.userProxy));updateShortAuctionBidStatus(this);var bidValue=$('#short_bid_'+this.id).val();if(isNaN(bidValue)||this.getNextBid()>parseInt(bidValue)){$('#short_bid_'+this.id).val(this.getNextBid());}}
if(this.bidoPrice!='hidden'){var priceToCompare=(this.status=='not started'?this.userProxy:this.price);var needToCompare=(this.status=='not started'&&!(this.userProxy)?false:true);var metVar='';var amountVar='';if((this.bidoPrice>priceToCompare)&&needToCompare){amountVar='$'+formatBidPrice(this.bidoPrice);metVar=(priceToCompare>0)?'not met':'';}else if((this.bidoPrice<=priceToCompare)&&needToCompare){amountVar='$'+formatBidPrice(this.bidoPrice);metVar='met';}else{amountVar=('$'+formatBidPrice(this.bidoPrice));metVar='';}
$('#bido_price_'+this.id+' .amount').text(amountVar);$('#bido_price_'+this.id+' .met').text(metVar);$('#bido_price_window_'+this.id+' .amount').text('US'.amountVar);$('#bido_price_window_'+this.id+' .met').text(metVar);}
if(this.userBid>0){$('#userBid_'+this.id).html('US $'+formatBidPrice(this.userBid,this.priceFormat));}
this.updateBlock();}
auction.getBlockId=function(){return'#auction_block_'+this.id;}
auction.getBlock=function(){return $(this.getBlockId());}
auction.updateBlock=function(){var block=this.getBlock();block.find('.userProxyHelp').show();var userProxyValue='US $'+formatBidPrice(this.userProxy,this.priceFormat);if(this.type==1){if(this.status=='opened'||this.status=='paused'||this.status=='extended'){if(this.price<this.userProxy){block.find('.userProxyTitle').html('Your max bid:');}else{block.find('.userProxyTitle').html('Your bid:');}}
if(this.userProxy<=0){userProxyValue='You have not bid yet';block.find('.userProxyHelp').hide();}}
block.find('.userProxy').html(userProxyValue);block.find('.startBid').html('US $'+formatBidPrice(this.startPrice,this.priceFormat));if(this.userBid>0){block.find('.userBid').html('US $'+formatBidPrice(this.userBid,this.priceFormat));}
var priceToCompare=(this.status=='not started'?this.userProxy:this.price);var needToCompare=(this.status=='not started'&&!(this.userProxy)?false:true);if(this.bidoPrice=='hidden'){block.find('.bidoPriceMet').html('Not met');}else if((this.bidoPrice>priceToCompare)&&needToCompare){block.find('.bidoPriceMet').html('US $'+formatBidPrice(this.bidoPrice)+' not met');}else if((this.bidoPrice<=priceToCompare)&&needToCompare){block.find('.bidoPrice').text('$'+formatBidPrice(this.bidoPrice));block.find('.bidoPriceMet').html(app.config.bidoPriceMetText.replace('{$bido_price}',formatBidPrice(this.bidoPrice)));}else{block.find('.bidoPrice').text('$'+formatBidPrice(this.bidoPrice));block.find('.bidoPriceMet').html('US $'+formatBidPrice(this.bidoPrice));}
this.nextBid=this.getNextBid();if(block.find('.bidWindow').css('display')=='none'){block.find('.bid').attr('value',this.nextBid);}
if(this.price){block.find('.currentBid').html('US $'+formatBidPrice(this.price,this.priceFormat));block.find('.currentBidAd').hide();}else{block.find('.currentBidAd').show();}
if(this.buyItNowPrice>0&&this.price>=Math.ceil(this.buyItNowPrice*app.config.binOfferPercent)){var window=$('#bid_window_'+this.id);block.find('.buyNow').remove();window.find('.buyNow').remove();var binBlockOpened=block.find('.buyItNowWindow').css('display')!='none';var binWindowOpened=window.find('.buyItNowWindow').css('display')!='none';block.find('.buyItNowWindow').remove();window.find('.buyItNowWindow').remove();if(binBlockOpened){block.find('.bidButtonContainer').show();}
if(binWindowOpened){window.find('.buyItNowWindow').show();}
if(!this.binBidPlaced){var removedBinHtml='N/A (<span class="help-initiator" onmouseover="showHelpProcess(tabHelpTexts.removed_bin, this);" onmouseout="cancelHelpShow();" onclick="expandStop(event); showHelp(tabHelpTexts.removed_bin, this);">?</span>)';block.find('.binPrice').html(removedBinHtml);window.find('.binPrice').html(removedBinHtml);$('#bin_price_'+this.id+' div').html(removedBinHtml);}}
if(this.userId&&this.highBidderId==this.userId){if(!this.userWinning){this.userWinning=true;if(eff){playColor('high',5000,$('#auction_block_'+this.id).find('.currentBid'));}}}else{if(this.userWinning){this.userWinning=false;if(eff){playColor('out',5000,block.find('.currentBid'));if($('#sound_off')[0]&&$('#sound_off')[0].className=="sound-active"){playSound('outbid');}}}}
block.find('.currentBid').css('color',this.getPriceColor());var len=this.bids.length();if(len>0){block.find('.bidsCount').html('('+len+')');block.find('.bidHistoryLink').show();}
if(this.price>Math.ceil(this.buyItNowPrice*app.config.binOfferPercent)){block.find('.buyNow').hide();}}
auction.init=function(opt){for(var i in opt){this[i]=opt[i];}}
auction.setDataAfterBid=function(response){this.userProxy=response.proxy?response.proxy:0;if(response.price){this.setPrice(response.price);}
if(response.bids_count){this.bidsCount=response.bids_count;}
if(response.high_bidder){this.highBidderId=response.high_bidder;}
this.showMessage(response);}
auction.showMessage=function(response){var block=this.getBlock();if(response.message&&typeof(response.result)!='undefined'){if(response.result==3){this.showBidWindow(true,true);}
block.find('.bidStatus').css('color',this.getMessageColor(response));block.find('.bidStatus').html(response.message);window.clearTimeout(this.messageTimerId);if(response.result!=5){this.messageTimerId=window.setTimeout('$("'+this.getBlockId()+' .bidStatus").text("")',this.messageDelay);}}}
auction.pause=function(pause){var block=this.getBlock();if(pause){pauseCountdown('timer_'+this.id,true);pauseCountdown('block_timer_'+this.id,true);pauseCountdown('block_timer_place_bid_'+this.id,true);$('#price_'+this.id).parent().hide();if(!$('#current_bid_'+this.id+' .paused').length){$('#current_bid_'+this.id).append('<div class="name-fixed paused" style="color:red">Paused</div>')}
$('#bidWindow').hide();block.find('.bidButtonContainer').hide();block.find('.pauseReason').html(this.pauseReason);block.find('.pauseWindow').show();}else{pauseCountdown('timer_'+this.id,false);pauseCountdown('block_timer_'+this.id,false);pauseCountdown('block_timer_place_bid_'+this.id,false);$('#current_bid_'+this.id).find('.paused').remove();$('#price_'+this.id).parent().show();$('.pauseWindow').hide();block.find('.bidButtonContainer').show();this.update();}}
auction.showBidWindow=function(show,showNextBid){var block=this.getBlock();if(show){if(showNextBid){block.find('.bid').val(this.nextBid);}
block.find('.buyItNowWindow').hide();block.find('.buyNow').hide();block.find('.bidWindow').show();block.find('.bidButtonContainer').hide();block.find('.bid').focus();}else{block.find('.bidWindow').hide();block.find('.buyNow').show();block.find('.bidButtonContainer').show();block.find('.bid').blur();if(showNextBid){block.find('.bid').val(this.nextBid);}}}
auction.showConfirmWindow=function(bid){var block=this.getBlock();block.find('.confirmBid').text(bid);block.find('.bidWindow').hide();block.find('.buyNow').hide();block.find('.bidButtonContainer').hide();block.find('.confirmWindow').show();}
auction.hideWindowAndPlaceBid=function(isOffer,confirmed){var block=this.getBlock();if(block.find('.confirmWindow:visible').length){block.find('.confirmWindow').hide();block.find('.bidButtonContainer').show();}else if(block.find('.buyItNowWindow:visible').length){block.find('.buyItNowWindow').hide();block.find('.bidButtonContainer').show();}else{this.showBidWindow(false);}
var bid=parseInt(block.find('.bid').val());var nextBid=this.nextBid;if(isNaN(bid)||bid!=block.find('.bid').val()){this.showBidWindow(true);alert('Please put in only full dollar amounts and only numbers, no decimals or commas.',function(){block.find('.bid').val((!isNaN(bid)&&bid>nextBid)?bid:nextBid);block.find('.bid').focus();});return false;}
if(bid<nextBid){this.showBidWindow(true);block.find('.bid').focus();var message="Sorry, the next minimum bid is: US $"+formatBidPrice(nextBid)+".";if(this.startPriceFromBidoPrice){message="The seller has selected this auction's starting bid to be the item's <a target=blank href=/Info/BidoPrice>BidoPrice</a> of $"+formatBidPrice(this.bidoPrice)+".<br> You must raise your bid to meet or exceed the BidoPrice in order to bid on this auction.";}
alert(message);return false;}
var comparePrice=Math.max(this.userProxy,this.price);if(!confirmed&&bid>app.config.auctionLargeIncreasePriceDetectFrom&&bid>comparePrice*app.config.auctionLargeIncreasePricePercent/100){this.showConfirmWindow(bid);return false;}
this.placeBidRequest(bid,isOffer);}
auction.placeBidRequest=function(bid,isOffer){var block=this.getBlock();$('.bidButton_'+this.id).hide();$('.buyNow').hide();$('#bidButtonLoad_'+this.id).fadeIn();if($('#bidWindowAuctionId').val()==this.id){$('.shortAuctionBuyItNowWindow').hide();$('#bid_window_'+this.id+' .bidBlock').show();$('#bid_block_'+this.id+' .button-popup').hide();$('#bid_block_'+auction.id+' .wait-message').show();}
if(app.main_auction&&app.main_auction.id==this.id&&$('#bidButton').length){showBidWindow(false,true);$('#bidButton').hide();$('#bidButtonLoad').fadeIn();}
block.find('.bidButton').hide();block.find('.bidButtonLoad').fadeIn();var status=this.placeBid(bid,isOffer,function(message){var response=JSJaCJSON.parse(message.getBody());if(app.main_auction&&app.main_auction.id==response.id){app.main_auction.setProxy(response);app.main_auction.update();$('#bidButtonLoad').hide();$('#bidButton').fadeIn();}
var auction=getShortAuction(response.id);auction.setProxy(response);auction.update();var block=auction.getBlock();block.find('.bidButtonLoad').hide();block.find('.bidButton').fadeIn();block.find('.buyNow').fadeIn();$('#bidButtonLoad_'+auction.id).hide();$('.bidButton_'+auction.id).fadeIn();if($('#bidWindowAuctionId').val()==auction.id){showShortAuctionBidMessage(response);updateShortAuctionBidStatus(auction);$('#bid_block_'+auction.id+' .wait-message').hide();if(response.bin){$('#bid_block_'+auction.id+' .placeBid').remove();$('#bid_block_'+auction.id+' .buyItNow').remove();}
$('#bid_block_'+auction.id+' .button-popup').fadeIn();}});if(!status){$('.shortAuctionBuyItNowWindow').show();$('#bid_window_'+this.id+' .bidBlock').hide();$('#bid_block_'+this.id+' .button-popup').show();$('#bid_block_'+auction.id+' .wait-message').hide();}}
auction.hideConfirmWindow=function(){var block=this.getBlock();block.find('.confirmWindow').hide();block.find('.bidWindow').show();}
auction.showBuyItNowWindow=function(){var block=this.getBlock();block.find('.bidWindow').hide();block.find('.bidButtonContainer').hide();block.find('.buyItNowWindow').show();}
auction.hideBuyItNowWindow=function(){var block=this.getBlock();block.find('.buyItNowWindow').hide();block.find('.bidButtonContainer').show();}
auction.recalcGaugeCode=function(type,newValue){var classes=[];var scales=gaugeScales[type];for(var i=0;i<=gaugeImageLevels;i++){classes.push(type+'-'+i);}
var state=0;var obj=$('#gauge_image_'+this.id+' .auction-stats');if(!obj.size()){return;}
for(var i in scales){if((scales[i]['min_value']===null||newValue>=scales[i]['min_value'])&&(scales[i]['max_value']===null||newValue<=scales[i]['max_value'])){state=scales[i]['value'];break;}}
var gaugeImageInTab='#gauge_image_'+this.id;var gaugeImageOnPage='#auction_gauge_image_'+this.id;$(gaugeImageInTab).add(gaugeImageOnPage).find('.auction-stats').removeClass(classes.join(' ')).addClass(type+'-'+state);}
return auction;}
function getShortAuction(id){if(typeof(app.live_auctions[id])!='undefined'){return app.live_auctions[id];}
if(typeof(app.upcoming_auctions[id])!='undefined'){return app.upcoming_auctions[id];}
if(typeof(app.partner_auctions[id])!='undefined'){return app.partner_auctions[id];}}

