var dwrite=document.write,
APP='a',
wxpauth=null,
wxpemail=null,
wxptrial=false,
webtext=null,
MAX={
projectLog:{from:20,to:20,summary:40,subject:20},
invite:{msgLength:500},
note:{length:5000},
upload:{bytes:25*1024*1024,timeout:30*1000}
},
sharedFolder={id:-1,name:'Received Mail',parentid:0},
toBeFiled='To Be Filed',
topFolder={id:0,name:'My Folders',parentid:0},
recipProject={id:-1,name:'Received Emails',folderid:0},
img=[],SYSINFO=[],login=[],profile=[],account=[],epmCredits=[],epmCreditFiles=[],folders=[],projects=[],subsidies=[],files=[],filesPending=[],users=[],
autologout_shown=false,
debuglog='',
DEBUG=0,
revpostal={
CA:{
A:'NL',
M:'ON',
B:'NS',
N:'ON',
C:'PE',
P:'ON',
E:'NB',
R:'MB',
G:'PQ',
S:'SK',
H:'PQ',
T:'AB',
J:'PQ',
V:'BC',
K:'ON',
X:'NW',
L:'ON',
Y:'YK'
}
},
provinces={
CA:{
AB:'Alberta',
BC:'British Columbia',
MB:'Manitoba',
NB:'New Brunswick',
NL:'Newfoundland and Labrador',
NS:'Nova Scotia',
NW:'Northwest Territories and Nunavut',
ON:'Ontario',
PE:'Prince Edward Island',
PQ:'Quebec',
SK:'Saskatchewan',
YK:'Yukon'
},
US:{
AL:'ALABAMA',
AK:'ALASKA',
AS:'AMERICAN SAMOA',
AZ:'ARIZONA',
AR:'ARKANSAS',
CA:'CALIFORNIA',
CO:'COLORADO',
CT:'CONNECTICUT',
DE:'DELAWARE',
DC:'DISTRICT OF COLUMBIA',
FM:'FEDERATED STATES OF MICRONESIA',
FL:'FLORIDA',
GA:'GEORGIA',
GU:'GUAM',
HI:'HAWAII',
ID:'IDAHO',
IL:'ILLINOIS',
IN:'INDIANA',
IA:'IOWA',
KS:'KANSAS',
KY:'KENTUCKY',
LA:'LOUISIANA',
ME:'MAINE',
MH:'MARSHALL ISLANDS',
MD:'MARYLAND',
MA:'MASSACHUSETTS',
MI:'MICHIGAN',
MN:'MINNESOTA',
MS:'MISSISSIPPI',
MO:'MISSOURI',
MT:'MONTANA',
NE:'NEBRASKA',
NV:'NEVADA',
NH:'NEW HAMPSHIRE',
NJ:'NEW JERSEY',
NM:'NEW MEXICO',
NY:'NEW YORK',
NC:'NORTH CAROLINA',
ND:'NORTH DAKOTA',
MP:'NORTHERN MARIANA ISLANDS',
OH:'OHIO',
OK:'OKLAHOMA',
OR:'OREGON',
PW:'PALAU',
PA:'PENNSYLVANIA',
PR:'PUERTO RICO',
RI:'RHODE ISLAND',
SC:'SOUTH CAROLINA',
SD:'SOUTH DAKOTA',
TN:'TENNESSEE',
TX:'TEXAS',
UT:'UTAH',
VT:'VERMONT',
VI:'VIRGIN ISLANDS',
VA:'VIRGINIA',
WA:'WASHINGTON',
WV:'WEST VIRGINIA',
WI:'WISCONSIN',
WY:'WYOMING',
AE:'Armed Forces Africa',
AA:'Armed Forces Americas',
AE:'Armed Forces Canada',
AE:'Armed Forces Europe',
AE:'Armed Forces Middle East',
AP:'Armed Forces Pacific'
}
},
countries={
US:'United States',
AF:'Afghanistan',
AX:'Aland Islands',
AL:'Albania',
DZ:'Algeria',
AS:'American Samoa',
AD:'Andorra',
AO:'Angola',
AI:'Anguilla',
AQ:'Antarctica',
AG:'Antigua and Barbuda',
AR:'Argentina',
AM:'Armenia',
AW:'Aruba',
AC:'Ascension Island',
AU:'Australia',
AT:'Austria',
AZ:'Azerbaijan',
BS:'Bahamas',
BH:'Bahrain',
BD:'Bangladesh',
BB:'Barbados',
BY:'Belarus',
BE:'Belgium',
BZ:'Belize',
BJ:'Benin',
BM:'Bermuda',
BT:'Bhutan',
BO:'Bolivia',
BA:'Bosnia and Herzegovina',
BW:'Botswana',
BV:'Bouvet Island',
BR:'Brazil',
IO:'British Indian Ocean Territory',
VG:'British Virgin Islands',
BN:'Brunei Darussalam',
BG:'Bulgaria',
BF:'Burkina Faso',
BI:'Burundi',
KH:'Cambodia',
CM:'Cameroon',
CA:'Canada',
CV:'Cape Verde',
KY:'Cayman Islands',
CF:'Central African Republic',
TD:'Chad',
CL:'Chile',
CN:'China',
CX:'Christmas Island',
CC:'Cocos (Keeling)Islands',
CO:'Colombia',
KM:'Comoros',
CG:'Congo',
CD:'Congo,Democratic Republic',
CK:'Cook Islands',
CR:'Costa Rica',
CI:'Cote D\'Ivoire (Ivory Coast)',
HR:'Croatia (Hrvatska)',
CU:'Cuba',
CY:'Cyprus',
CZ:'Czech Republic',
CS:'Czechoslovakia (former)',
DK:'Denmark',
DJ:'Djibouti',
DM:'Dominica',
'DO':'Dominican Republic',
TP:'East Timor',
EC:'Ecuador',
EG:'Egypt',
SV:'El Salvador',
GQ:'Equatorial Guinea',
ER:'Eritrea',
EE:'Estonia',
ET:'Ethiopia',
MK:'F.Y.R.O.M. (Macedonia)',
FK:'Falkland Islands (Malvinas)',
FO:'Faroe Islands',
FJ:'Fiji',
FI:'Finland',
FR:'France',
FX:'France,Metropolitan',
GF:'French Guiana',
PF:'French Polynesia',
TF:'French Southern Territories',
GA:'Gabon',
GM:'Gambia',
GE:'Georgia',
DE:'Germany',
GH:'Ghana',
GI:'Gibraltar',
GB:'Great Britain (UK)',
GR:'Greece',
GL:'Greenland',
GD:'Grenada',
GP:'Guadeloupe',
GU:'Guam',
GT:'Guatemala',
GN:'Guinea',
GW:'Guinea-Bissau',
GY:'Guyana',
HT:'Haiti',
HM:'Heard and McDonald Islands',
HN:'Honduras',
HK:'Hong Kong',
HU:'Hungary',
IS:'Iceland',
'IN':'India',
ID:'Indonesia',
IR:'Iran',
IQ:'Iraq',
IE:'Ireland',
IM:'Isle of Man',
IL:'Israel',
IT:'Italy',
JM:'Jamaica',
JP:'Japan',
JE:'Jersey',
JO:'Jordan',
KZ:'Kazakhstan',
KE:'Kenya',
KI:'Kiribati',
KP:'Korea (North)',
KR:'Korea (South)',
KW:'Kuwait',
KG:'Kyrgyzstan',
LA:'Laos',
LV:'Latvia',
LB:'Lebanon',
LS:'Lesotho',
LR:'Liberia',
LY:'Libya',
LI:'Liechtenstein',
LT:'Lithuania',
LU:'Luxembourg',
MO:'Macau',
MG:'Madagascar',
MW:'Malawi',
MY:'Malaysia',
MV:'Maldives',
ML:'Mali',
MT:'Malta',
MH:'Marshall Islands',
MQ:'Martinique',
MR:'Mauritania',
MU:'Mauritius',
YT:'Mayotte',
MX:'Mexico',
FM:'Micronesia',
MD:'Moldova',
MC:'Monaco',
MN:'Mongolia',
ME:'Montenegro',
MS:'Montserrat',
MA:'Morocco',
MZ:'Mozambique',
MM:'Myanmar',
NA:'Namibia',
NR:'Nauru',
NP:'Nepal',
NL:'Netherlands',
AN:'Netherlands Antilles',
NT:'Neutral Zone',
NC:'New Caledonia',
NZ:'New Zealand (Aotearoa)',
NI:'Nicaragua',
NE:'Niger',
NG:'Nigeria',
NU:'Niue',
NF:'Norfolk Island',
MP:'Northern Mariana Islands',
NO:'Norway',
OM:'Oman',
PK:'Pakistan',
PW:'Palau',
PS:'Palestinian Territory,Occupied',
PA:'Panama',
PG:'Papua New Guinea',
PY:'Paraguay',
PE:'Peru',
PH:'Philippines',
PN:'Pitcairn',
PL:'Poland',
PT:'Portugal',
PR:'Puerto Rico',
QA:'Qatar',
RE:'Reunion',
RO:'Romania',
RU:'Russian Federation',
RW:'Rwanda',
GS:'S. Georgia and S. Sandwich Isls.',
KN:'Saint Kitts and Nevis',
LC:'Saint Lucia',
VC:'Saint Vincent &the Grenadines',
WS:'Samoa',
SM:'San Marino',
ST:'Sao Tome and Principe',
SA:'Saudi Arabia',
SN:'Senegal',
RS:'Serbia',
SC:'Seychelles',
SL:'Sierra Leone',
SG:'Singapore',
SK:'Slovak Republic',
SI:'Slovenia',
SB:'Solomon Islands',
SO:'Somalia',
ZA:'South Africa',
ES:'Spain',
LK:'Sri Lanka',
SH:'St. Helena',
PM:'St. Pierre and Miquelon',
SD:'Sudan',
SR:'Suriname',
SJ:'Svalbard &Jan Mayen Islands',
SZ:'Swaziland',
SE:'Sweden',
CH:'Switzerland',
SY:'Syria',
TW:'Taiwan',
TJ:'Tajikistan',
TZ:'Tanzania',
TH:'Thailand',
TG:'Togo',
TK:'Tokelau',
TO:'Tonga',
TT:'Trinidad and Tobago',
TN:'Tunisia',
TR:'Turkey',
TM:'Turkmenistan',
TC:'Turks and Caicos Islands',
TV:'Tuvalu',
UM:'US Minor Outlying Islands',
SU:'USSR (former)',
UG:'Uganda',
UA:'Ukraine',
AE:'United Arab Emirates',
UK:'United Kingdom',
UY:'Uruguay',
UZ:'Uzbekistan',
VU:'Vanuatu',
VA:'Vatican City State (Holy See)',
VE:'Venezuela',
VN:'Viet Nam',
VI:'Virgin Islands (U.S.)',
WF:'Wallis and Futuna Islands',
EH:'Western Sahara',
YE:'Yemen',
YU:'Yugoslavia (former)',
ZR:'Zaire',
ZM:'Zambia',
ZW:'Zimbabwe'
},
FILEICON={
'message/rfc822':'/icons/quill.gif',
'text/html':'/icons/layout.png',
'text/plain':'/icons/text.png',
'application/pdf':'/icons/pdf.png',
'application/x-pdf':'/icons/pdf.png',
'application/msword':'/icons/c.png',
'application/zip':'/icons/compressed.png',
'image/jpeg':'/icons/image2.png',
'image/png':'/icons/image2.png',
'image/gif':'/icons/image2.png',
'image/bmp':'/icons/image2.png',
'video/mpeg':'/icons/sound1.png',
'audio/mpeg':'/icons/sound1.png',
'audio/x-wav':'/icons/sound1.png',
other:'/icons/binary.png'
},
FILETYPE={
OTHER:'other',
EMAIL:'email'
},
nums='0123456789',
alphabet='ABCDEFGHIJLKMNOPQRSTUVWXYZabcdefghijlkmnopqrstuvwxyz',
alphahex='0123456789ABCDEF',
posts=nums+alphabet+'-',
alphaemail=alphabet+nums+'@.-_',
lets=posts+'.\' ?$#';


function preloadImages(){

var gif=['1','loading3','progress'
],
png=['wxpall','wxpbg'
],
jpg=[];

for(var i=0;i<gif.length;i++)
preloadImage(gif[i],'gif');
for(var i=0;i<png.length;i++)
preloadImage(png[i],'png');
for(var i=0;i<jpg.length;i++)
preloadImage(jpg[i],'jpg');
}
function preloadImage(name,ext){
debug('preloadImage('+name+'.'+ext+')');
var i=new Image();
i.name=name;
i.onload=function(){preloadImageDone(name);i.onload=noop;};
img[name]=i;
i.src='i/'+name+'.'+ext;
}
function preloadImageDone(name){
debug('preloadImageDone('+name+')'+stackTrace());
img[name].done=1;
}
function oncePreloadImageDone(fcn){
var n=0,k=0;
for(var i in img){
n++;
if(img[i].done)k++;
}
if(n==k)
return fcn();
setTimeout(function(){oncePreloadImageDone(fcn)},1000);
}

function S(w,bor){

bor=bor?'class=border border=1':'';
return '<img src=i/1.gif '+bor+' height=1 width='+w+' />';
}
function VS(h){

return '<img src=i/1.gif height='+h+' width=1>';
}


function updateAccountBalance(){

var data='list=credits'
+'&start='+getVal('start')
+'&end='+getVal('end')
+'&wxpauth='+wxpauth;
resp=ckajax.getText(base(data),data);

if(resp.indexOf('Error:')!=-1)
return floatError(resp);

var R=parseResponse(resp),
d=new Date();
if(R.currentTime)
currentTimeDelta=Math.floor(d.getTime()/1000)-tzOffset()-R.currentTime;

epmCredits=R.epmCredits;
epmCreditFiles=R.creditFiles;

showAccountBalance();
}

function tree_loadData(callback){
debug('tree_loadData('+callback+')');
wxpLoading();
ckajax.clearCache();
var data='list=all&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function tree_loadData_ajax(stat,statStr,resp){

if(stat!=200)
return floatError('Server unavilable,check connection and try again. (Status: '+stat+')');
if(resp.length==0)
return floatError('Error: No response from server');
if(resp.indexOf('Error: Please try again later')!=-1)
return floatError(wtext('purchaseCredits.internalError'));
if(resp.indexOf('Error:')!=-1)
return floatError(justErrorResp(resp));

var R=parseResponse(resp),
d=new Date();
if(R.currentTime)
currentTimeDelta=Math.floor(d.getTime()/1000)-tzOffset()-R.currentTime;
autologout_shown=false;

login.now=R.login[0];
wxpemail=unescape(login.now.email).toLowerCase();
login.last=R.login[1];

epmCredits=R.epmCredits;
epmCreditFiles=R.creditFiles;

profile=R.profile[0];
profile.firm=R.firm[0];
if(R.group)
for(var i=0;i<R.group.length;i++)
R.group[i].name=b64dec(R.group[i].name);
profile.groups=R.group;
profile.clients=R.client;
profile.clerks=R.clerk

showAccountBalance();

if(profile.verified=='MISSING_TNC')
return agreeTAC();

showLoginInfo();

folders=[];
if(R.folders){
folders=R.folders;
quicksort(folders,name_cmp);
for(var i=0;i<folders.length;i++){
folders[i].name=b64dec(folders[i].name);
if(folders[i].participants)
folders[i].participants=folders[i].participants.split(';');
}
}

projects=[recipProject];
getRecipProjectByUserId.proj=null;
if(R.projects){
for(var i=0;i<R.projects.length;i++)
projects[1+i]=R.projects[i];
quicksort(projects,name_cmp);
for(var i=0;i<projects.length;i++){
if(projects[i].id==recipProject.id)continue;
projects[i].name=b64dec(projects[i].name);
projects[i].participants=projects[i].participants.split(';');
}
}

users=[];
if(R.users){
users=R.users;
for(var i=0;i<users.length;i++)
users[i].name=b64dec(users[i].name);
}

var html='';
files=[];
if(R.files){
files=R.files;

for(var i=0;i<files.length;i++){
if(files[i].collabprojectid*1)
files[i].projectid=files[i].collabprojectid;
else if(files[i].userid!=getUserId())
files[i].projectid=getRecipProjectByUserId(files[i].userid);
files[i].name=b64dec(files[i].name);
}
}

if(R.sysadmin){
html='['+iLink('showAdmin()','Admin')+']<br/>';
if(R.syskey[0]=='false')
adminSysKey();
}
gel('sysadmin').innerHTML=html;


html='';
var L=[iLink('fH();createGroup()',wtext('main.createGroup'))],G=profile.groups;
if(G)
for(var i=0;i<G.length;i++)
if(G[i].type=='admin')
L[L.length]=iLink('fH();showGroupAdmin('+G[i].id+')',G[i].name);
html=floatMenu(wtext('main.groupAdmin'),L)+'<br/>';
gel('groupAdmin').innerHTML=html;

gel('userReport').innerHTML='['+iLink('fH();askReport(\'user\')','Usage Report')+']<br/>';


html='';
var L=[],C=profile.clients;
if(C){
if(getCookie('wxpsuper')!=''){
html='['+iLink('fH();clerkGhostUser(-1)',bold('<span style="color:red">Stop Clerking</span>'))+']<br/>';
}else{
for(var i=0;i<C.length;i++)
L[L.length]=iLink('fH();clerkGhostUser('+i+')',showEmail(parseEmail(C[i])));
L[L.length]=iLink('fH();askClerk()','Become someone\'s clerk');
html=floatMenu('Clerk Admin',L)+'<br/>';
}
}
gel('clerkAdmin').innerHTML=html;









filesPending=R.pending?R.pending:[];
html='';
if(filesPending.length!=0)
html='['+iLink('showFilesPending()',wtext('main.filesPending'))+']<br/>';
gel('filesPending').innerHTML=html;

SYSINFO=R.WXPINFO;
len=SYSINFO.length;
for(var i=0;i<len;i++){
for(var k in SYSINFO[i]){
SYSINFO[k]=b64dec(SYSINFO[i][k]);
if(k=='credit.schedule'){
var r={},a=SYSINFO[k].split('\n');
for(var j=0;j<a.length;j++){
var b=a[j].split('='),
c=b[1].split(',');
r[b[0]]=[];
for(var l=0;l<c.length;l++){
var d=c[l].split(':');
r[b[0]][d[0]]=d[1]*1;
}
}
SYSINFO[k]=r;
}
}
}

wxptrial=R.trialAccount==1;


tree_build();


var view=getwxpview();
if(view.indexOf('fileid=')!=-1){
var fw=view.split('=');
showFileJump(fw[1]);
}
else if(view!=''){
var fw=view.split('x');
if(fw[1]!=0&&getProjectById(fw[1])){
if(fw[0]!=-1&&!getFolderById(fw[0]))
fw[0]=null;
showProject(fw[0],fw[1],false,fw[2],fw[3]);
tree_scroll(fw[0],fw[1]);
}else{
if(fw[0]==-1||getFolderById(fw[0])){
showFolder(fw[0]);
tree_scroll(fw[0]);
}
else if(fw[0]==0)
tree_show(0,0);
}
}

if(callback)
return setTimeout(callback,500);

});
}

function adminSysKey(){

var t='adminSysKey.';

floatAsk(wtext(t+'title'),wtext(t+'body',{}),
[button(wtext('next'),'adminSysKeyDo()')]
);
gel('syskey').focus();
}
function adminSysKeyDo(){

var key=getVal('syskey'),
data='adminSysKey=1'
+'&key='+key
+'&wxpauth='+wxpauth;

fH();
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error:')!=-1)
return floatError(resp,'tree_loadData()');
});

tree_loadData();
}


function isSysAdmin(){

return sysadmin.searchView=='sysAdmin';
}
function isFirmAdmin(gid){

return profile.firm.type=='admin';
}
function isGroupAdmin(gid){

var G=profile.groups;
if(G)
for(var i=0;i<G.length;i++)
if((!gid||gid==G[i].id)&&G[i].type=='admin')
return true;
return false;
}


function tree_scroll(fid,pid){
var o;
o=pid?gel('treew'+pid):gel('treef'+fid);
gel('treeDIV').scrollTop=getObjectOffset(o).y-getObjectOffset(gel('treeTable')).y;
}

function getCurrentTreeView(){
var V=getwxpview().split('x');
V[0]*=1;
V[1]*=1;

return 'Current selection:<br/>'+getTreeView(V[0],V[1]);
}

function tree_show(fid,pid){
if(!tree_show.last)
tree_show.last={pid:0,fid:-2};

showEmailTabHeaders('EMAIL');
gel('searchSel_label').onmouseover=function(){floatNearShow('searchSel_label',getCurrentTreeView(),1);};
debug('tree_show('+fid+','+pid+')');
fid *=1;
pid *=1;
if(fid==0)
setwxpview('0x0x0x0');

var F=getFolderById(fid);
if(fid==-1)
F=sharedFolder;
toggleTree(fid,pid!=0);

if(fid!=0){
F=getFolderById(F.parentid);
while(F&&F.id){
toggleTree(F.id,1);
F=getFolderById(F.parentid);
}
toggleTree(0,1);
}

if(fid==0)
gel('emailDIV').innerHTML=wtext('thisisRoot.html',{WXPNAME:SYSINFO.name});
else if(pid!=0&&getFolderById(fid)==null)
fid=null;

var W;
if(W=gel('treew'+tree_show.last.pid))
W.style.color=(tree_show.last.pid <0)?'#0082cc':'#000000';
tree_show.last.pid=pid;
if(W=gel('treew'+pid))
W.style.color='#0000ff';

debug('tree_show fid='+fid+' pid='+pid+' last='+tree_show.last.fid);
if(tree_show.last.fid!=-2&&(F=gel('treef'+tree_show.last.fid)))
F.style.color=F.oldcolor?F.oldcolor:'';
if(!pid){
if(F=gel('treef'+fid)){
F.oldcolor=F.style.color;
F.style.color='#0000ff';
}
tree_show.last.fid=fid;
}
}

function tree_build(){

var T=gel('treeDIV'),
E=gel('emailDIV'),
html='';


html+=tree_(topFolder,'showFolder','showProject');

if(!T)return;

T.innerHTML='<table id=treeTable style="border-collapse:collapse;padding:0px;width:100%"><tr><td style="padding:0px">'+html+'</td></tr></table>';
}

function tree_over(e){
e.onmouseout=function(){e.style.textDecoration='none'; };
e.style.textDecoration='underline';
}
var tree={last:null,n:0};
function tree_sel(el){
debug('tree_sel('+el+')');
var l=tree.last;
if(l!=null)
l.style.backgroundColor=l.oldbgcolor;
else if((l=gel('tree_last'))!=null)
l.style.backgroundColor=l.oldbgcolor;

if(!el)
return tree.last=null;

el.oldbgcolor=el.style.backgroundColor;
el.style.backgroundColor='#cccccc';
tree.last=el;

if(!el.id)
return;
var id=strReplace(el.id,'treer',''),
s=gel('tree'+id).style;

if(s.display=='none'){
s.display='';
qImgSet('treei'+id,'minus');
}else{
s.display='none';
qImgSet('treei'+id,'plus');
}
}
function tree_(F,Ffcn,Wfcn,trk){
var sty='font:normal 12px Lucida,sans-serif;font-weight:bold;text-align:left;padding:3px 0px 3px 3px;width:100%;',
ovr='" onmouseover="tree_over(this)';
debug('tree_('+F+','+Ffcn+','+Wfcn+','+trk+')');

var trkid='';
if(trk){
trk='tree_sel(this);';
trkid='.'+tree.n;
}else{
trk='';
}

var html='',hil='',
subw=0,subFn=0,subF='';

if(F==sharedFolder||F.name==toBeFiled)
hil='color:#0082cc;';

for(var i=0;i<folders.length;i++)
if(folders[i].parentid==F.id)
subF+=tree_(folders[i],Ffcn,Wfcn,trk);

html+=parseTmpl('<table style="width:100%;padding:0px" border=0 class=tight>\n'+
'<tr style="cursor:pointer;background:#f2f2f2" id="treer{ID}" onclick="try{{CLK}}catch(e){floatError(e)}">\n'+
'<td valign=center><table class=tight style="background:#ffffff"><tr><td id="treei{ID}" style="padding:0px;border-collapse:collapse;width:11px;background:#ffffff url(i/wxpall.png) no-repeat -544px -216px"><img src=i/1.gif width=11 height=11 /></td></tr></table></td>\n'+
'<td id="treef{ID}" style="{EXTRA}">{NAME}</td>\n'+
'</tr>\n'+
'<tr><td></td><td>\n'+
'<table id="tree{ID}" style="width:100%;padding:1px 1px 1px 0px;border-collapse:collapse;display:none" border=0>\n'+
'<tr><td>{*S:10}</td></tr>',
{ID:F.id+trkid,CLK:trk+Ffcn+'('+F.id+')',EXTRA:sty+hil+ovr,NAME:F.name,ITEMS:countSubItems(F.id)});

if(!trk&&F==topFolder){
hil='color:#0082cc;';


var P=getRecipProjectByUserId.proj;
for(var i in P){
if(i.indexOf('id')==0)
html+=parseTmpl('<tr onclick="try{{CLK}}catch(e){floatError(e)}"><td align=center>-</td><td style="cursor:pointer;{EXTRA}" id=treew{ID}>{NAME}({FILES})</td></tr>\n',
{ID:P[i].id,FID:0,NAME:P[i].name,FILES:countFiles(P[i].id),EXTRA:hil+sty+ovr,CLK:Wfcn+'('+0+','+P[i].id+')'});
}
hil='';
}

if(Wfcn){
for(var i=0;i<projects.length;i++){
if(projects[i].folderid==F.id&&projects[i].id!=recipProject.id){
subw++;
var hil=(projects[i].id==recipProject.id)? 'color:#0082cc;':'';
html+=parseTmpl('<tr onclick="{CLK}"><td align=center>-</td><td style="cursor:pointer;{EXTRA}" id=treew{ID}>{NAME}({FILES})</td></tr>\n',
{ID:projects[i].id,FID:F.id,NAME:projects[i].name,FILES:countFiles(projects[i].id),EXTRA:hil+sty+ovr,CLK:trk+Wfcn+'('+F.id+','+projects[i].id+')'});
}
}
}

if(subF.length!=0){
html+='<tr><td colspan=2 style="width:100%;padding:0px;">\n'+
subF+
'</td></tr>\n';
}

if(trk==''&&subF==''&&subw==0&&F!=topFolder)
html+='<tr><td>'+S(10)+'</td><td style="font-style:italic;color:#cccccc;'+sty+'">(empty)</td></tr>\n';

html+='</table>\n'+
'</td></tr></table>\n';
return html;
}

function toggleTree(n,show){
debug('toggleTree('+n+','+show+')');
var T=gel('tree'+n);
if(!T)return;
if(show||T.style.display=='none'){
T.style.display='';
qImgSet('treei'+n,'minus');
}else{
T.style.display='none';
qImgSet('treei'+n,'plus');
}
}

function salvageEmail(msgid,addRule){

var data='salvageEmail='+msgid
+'&addRule='+addRule
+'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
alert(resp);
});
}

var imgLink_a={n:1000,o:[]};
function imgLinkPad(clk,imgOut,imgOver,id,w,h,txt){
return imgLink(clk,imgOut,imgOver,id,w,h,'<span style="padding:0px 3px 0px 0px">'+txt+'</span>');
}
function imgLink(clk,imgOut,imgOver,id,w,h,txt){

if(!id||id=='')
id='imgLink'+imgLink_a.n++;
if(w&&w!='')
w='width:'+w+';';
if(h&&h!='')
h='height:'+h+';';
if(!w)w='';
if(!h)h='';
if(!txt)txt='';

imgLink_a.o[id]={CODE:clk,OUT:imgOut,OVR:imgOver,ID:id,W:w,H:h,TXT:txt};

var d='{W}'+' '+'{H}',
r=parseTmpl('<table class=tight style="'+d+'"><tr><td id={ID}'+
' style="'+d+' background:url({OUT});font:bold normal 10px Lucida,sans-serif"'+
' align=right valign=center'+
' onclick="try{{CODE}}catch(e){floatError(e);}return false"'+
' onmouseover="imgLinkOver(this,\'{OVR}\')"'+
'>{TXT}</td></tr></table>',
imgLink_a.o[id]);

return r;
}
function imgLinkOver(L,img){
var S=L.style,
O=imgLink_a.o[L.id];
L.onmouseout=function(){
S.cursor='default';
S.background=strReplace(S.background,O.OVR,O.OUT);
}
S.cursor='pointer';
S.background=strReplace(S.background,O.OUT,O.OVR);
}
function iSubmit(v){
if(!v)v='Submit';
return '<input type=submit value="'+v+'" style="padding:0px;margin:2px;font-size:10px" />';
}
function iLink(code,txt,id,sty){

id=id?'id="'+id+'"':'';
sty=sty?'style="'+sty+'"':'';

return '<a href="javascript:'+code+'" '+sty+' onclick="try{'+code+';}catch(e){floatError(e);}return false;" '+id+'>'+txt+'</a>';
}
function td(t,id){
id=id?'id="'+id+'"':'';
return '<td '+id+'>'+t+'</td>';
}
function tdS(v){return '<td style="border:0px;padding:0px 0px 0px 0px">'+S(v)+'</td>'; }
function tdnote(t,clk,id,mono){
id=id?'id="'+id+'"':'';
return '<td '+id+' valign=middle style="border:1px solid #000000;'+(mono?'font-family:monospace':'')+'" onclick="try{'+clk+'}catch(e){floatError(e)}">'+t+'</td>';
}
function tdr(t,id){return '<td'+(id?' id='+id:'')+' align=right>'+t+'</td>'; }
function tdl(t){return '<td align=left>'+t+'</td>'; }
function tdlnw(t){return '<td align=left style="white-space:nowrap">'+t+'</td>'; }
function trtdlnw(t){return '<tr>'+tdlnw(t)+'</tr>'; }
function tdt(t){return '<td valign=top>'+t+'</td>'; }
function tdtr(t){return '<td valign=top align=right>'+t+'</td>'; }
function bold(t){return '<b>'+t+'</b>'; }
function nobr(t){return '<nobr>'+t+'</nobr>'; }

function showFilesPending_ipaddr(n){

var t='emailRule.addHost.',
F=filesPending[n];
floatAsk(wtext(t+'title'),
wtext(t+'body',{HOST:F.dnsaddr,IP:F.ipaddr,EMAIL:F.from,FROM:F.from,SUBJECT:b64dec(F.subject)}),
[button(wtext('cancel'),'fH(2);blanketScreen()'),
button(wtext(t+'allowOnce'),'salvageEmail(\''+F.msgid+'\',false)'),
button(wtext(t+'allowAlways'),'salvageEmail(\''+F.msgid+'\',true)')],
2
);
}

function showFilesPending(){

var t='listPending.',
html=wtext(t+'head'),
numCred=0,
reasonExplain={
'IPAddr/Hostname mismatch':'IPAddr/Hostname mismatch',
'No credits found':'No credits found',
'From mismatch':'Sender not in thread',
'_':0
};
reasonResolve={
'IPAddr/Hostname mismatch':'showFilesPending_ipaddr',
'No credits found':'purchaseCredits',
'Not a recipient':'purchaseCredits',
'_':0
};
for(var i=0;i<epmCredits.length;i++)
numCred+=epmCredits[i].quantity-epmCredits[i].consumed;

for(var i=0;i<filesPending.length;i++){
var F=filesPending[i],
rexpl=function(F){
var s=b64dec(F.reason);
for(var k in reasonExplain)
if(s.indexOf(k)!=-1)
return reasonExplain[k];
return s;
};
if(F.dnsaddr=='')
F.dnsaddr='<i>no dns</i>';

var replace={
FROM:F.from,
SUBJECT:b64dec(F.subject),
SIZE:humanSize(F.size),
DATE:floatTime(F.datetime),

REASON:rexpl(F),
PROCESSNOW:button(wtext(t+'processNow'),'pendingProcessNow(\''+F.msgid+'\')')
};
if(numCred==0)
replace.PROCESSNOW=button(wtext(t+'buyCredits'),'purchaseCredits()');
html+=wtext(t+'row',replace);
}

html+='</table>';

floatAsk(wtext(t+'title'),
html,
[button(wtext('close'),'fH()')]
);
}

function pendingProcessNow(msgid){
var t='listPending.done.',
data='pendingProcessNow='+msgid
+'&wxpauth='+wxpauth;

floatProgress();
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error:')!=-1)
return floatError(resp);

fH();
wxpRefresh();

floatAsk(wtext(t+'title'),wtext(t+'body'),
[button(wtext('close'),'fH()')]
);
});
}

function arrecmp(a,f){

for(var i=0;i<a.length;i++)
if(!f(a[i]))
return false;
return true;
}

function getSearchValues(adv){
var S={

start:'Jan 01 2010',
end:'Dec 31 2099',
from:'',
to:'',
subject:'',
adv:adv,
simple:''
};

debug('getSearchValues test='+getVal('search_from','bogus'));
S.start=getVal('search_cal','Jab 01 2010');
S.start=getVal('search_start',S.start);
if(iCalTime('g',S.start)>iCalTime('g',iCalToday()))
iCalSet('search_cal',iCalSet('search_start',S.start=iCalToday()));

S.end=getVal('search_end',S.end);
if(iCalTime('g',S.end)<iCalTime('g',S.start))
iCalSet('search_end',S.end=S.start);

if((S.recip=getVal('search_recip',S.recip))=='Recipients')
S.recip='';
if((S.subject=getVal('search_subject',S.subject))=='Subject')
S.subject='';
if((S.simple=getVal('search',S.simple))=='Search')
S.simple='';
debug('getSearchValues from getVal()='+print_r(S));

if(S.adv)
S.simple='';



return S;
}
function showAdvancedSearch(){
showEmailTabHeaders('ADVSEARCH');
}
function showSimpleSearch(){
showEmailTabHeaders('SEARCH');
}

function searchReg(){
var adv=gel('advSearchViewText').style.display=='';
debug('searchReg selection='+gel('searchSel').checked+'  adv='+adv+'  view='+getwxpview());
var S=getSearchValues(adv),
view=getwxpview(),
P=getProjectById(view.split('x')[1]),
data='search=1'
+'&timeOffset='+currentTimeDelta
+'&searchSel='+(gel('searchSel').checked?view:'')
+'&project='+escape(P?P.name:'')
+'&simple='+escape(S.simple)
+'&start='+S.start
+'&end='+S.end
+'&recip='+escape(S.recip)
+'&subject='+escape(S.subject)
+'&wxpauth='+wxpauth;

resortProjectEnable(false);

wxpLoading('emailDIV');
ckajax.getText(base(data),data,function(stat,statStr,resp){
debug('searchReg:'+resp);
var msg=null;
if(resp.indexOf('Error: Search too short')!=-1)
msg=resp;
else if(resp.indexOf('Error:')!=-1)
return floatError(resp);
var R=parseResponse(resp);
R=R['log'];
if(!R)
R=[];
showRegSearchTable(R,S,msg);
});
}

function getTreeViewSimple(fid,pid){
debug('getTreeViewSimple('+pid+')');
var ret='',
F=null;

if(pid){
if(getProjectById(pid)==null)
return alert('donno this project pid='+pid);

var W=getProjectById(pid);
ret=W.name;
fid=W.folderid;
}

F=getFolderById(fid);
if(fid==-1)F=sharedFolder;
while(F){
ret=F.name+'&nbsp;&nbsp;&gt;&nbsp;&nbsp;'+ret;
F=getFolderById(F.parentid);
}
F=topFolder;
ret=F.name+'&nbsp;&nbsp;&gt;&nbsp;&nbsp;'+ret;

return ret;
}

function getTreeView(fid,pid){
debug('getTreeView('+pid+')');
var ret='',
F=null;

if(pid){
if(getProjectById(pid)==null)
return wxpRefresh(function(){getTreeView(fid,pid)});

var W=getProjectById(pid);
ret='<table class=tight><tr><td style="padding:0px;font:bold normal 12px Lucida,sans-serif;text-align:left;">-&nbsp;'+W.name+'</td></tr></table>';
fid=W.folderid;
}

F=getFolderById(fid);
if(fid==-1)F=sharedFolder;
while(F){
ret='<table class=tight>'+
'<tr>'+
'<td style="padding:1px;vertical-align:middle"><table class=tight><tr><td style="background:#fff url(i/wxpall.png) no-repeat -533px -216px"><img width=11 height=11 src=i/1.gif /></td></tr></table></td>'+
'<td style="padding:1px 0px 1px 0px;font:normal 12px Lucida,sans-serif;font-weight:bold;text-align:left;">'+F.name+'</td>'+
'</tr>'+
'<tr><td>'+S(10)+'</td><td>'+ret+'</td></tr>'+
'</table>\n';
F=getFolderById(F.parentid);
}
F=topFolder;
ret='<table class=tight>'+
'<tr>'+
'<td style="padding:1px;vertical-align:middle"><table class=tight><tr><td style="background:#fff url(i/wxpall.png) no-repeat -533px -216px"><img width=11 height=11 src=i/1.gif /></td></tr></table></td>'+
'<td style="padding:1px 0px 1px 0px;font:normal 12px Lucida,sans-serif;font-weight:bold;text-align:left;">'+F.name+'</td>'+
'</tr>'+
'<tr><td>'+S(10)+'</td><td>'+ret+'</td></tr>'+
'</table>\n';

return ret;
}
function showRegSearchTable(R,S,msg){

qTrBg=['#ffffff','#f2f2f2'];qTrN=0;
var t='search.result.',
_td0=function(s){return '<td style="color:#ffffff;">'+s+'</td>\n'; },
_td=function(s){return '<td style="font:normal normal 10px Lucida,sans-serif;color:#ffffff;padding:1px;" valign=center>'+s+'</td>\n'; },
lastpid=0,
html=iForm('searchReg()')+
'<table class=pad id=noteTable>',
notes=[];


for(var i=0;i<R.length;i++){
var r=R[i];
if(r.projectid==0)
r.projectid=getFileById(r.fileid).projectid;
}

for(var i=0;i<R.length;i++){
var r=R[i];
if(r.projectid!=lastpid){
html+=genNotesTableRows(notes,1);
notes=[];
html+='<tr><td colspan=5>'+getTreeViewSimple(0,r.projectid)+'</td></tr>\n';
}
lastpid=r.projectid;
r.text=b64dec(r.text);
notes[notes.length]=r;
}
if(notes.length!=0)
html+=genNotesTableRows(notes,1);
html+='<tr style="border:0px">'+
tdS(1)+
tdS(84)+
tdS(44)+
tdS(192)+
tdS(304)+
'</tr>\n'+
'</table></form>';

if(msg)
html+='<i>'+msg+'</i><br/>';
if(R.length==0)
html+='<i>No matching results found</i><br/>';

gel('emailDIV').innerHTML=html;

debug('set start='+S.start);
iCalSet('search_start',S.start);
iCalSet('search_end',S.end);

gel('checkallSpan').style.display='none';
showEmailTabHeaders(S.adv?'ADVSEARCH':'SEARCH');
}

function wxpRefresh(fcn){
debug('wxpRefresh()');

window.onkeypress=wxpKeyPress;
tree_loadData(fcn);
}

function showFolder(fid){
debug('showFolder('+fid+')');
gel('emailDIV').scrollTop=0;

tree_show(fid,0);
if(fid==0)return;

var F=getFolderById(fid),
ED=gel('emailDIV');
if(!F)
F=sharedFolder;
if(F==sharedFolder)
ED.innerHTML=wtext('thisisShared.html',{FID:fid,NAME:F.name});
else if(F.name==toBeFiled)
ED.innerHTML=wtext('thisisToBeFiled.html',{FID:fid,NAME:F.name});
else{
debug(wtext('thisisFolder.html'));
ED.innerHTML=wtext('thisisFolder.html',{FID:fid,NAME:F.name});
}




setwxpview(fid+'x0x0x0');

if(fid==0)return;

var F=getFolderById(fid);
if(fid==-1)F=sharedFolder;
if(F==null)return floatError('Could not find folder (fid='+fid+')');

if(0){
var html=
bold(F.name)+'<br/>\n';

if(fid==-1){
ED.innerHTML=wtext('thisisShared.html',{WXPNAME:SYSINFO.name});
}else{





}


}
if(fid!=-1&&countSubItems(fid)!=0)
disableButton('delFolderButton');
}

var showProject_newest=false;
function showProject(fid,pid,refresh,fileid,noteid){
gel('fileaction').disabled=1;
resortProjectEnable(true);
gel('emailDIV').scrollTop=0;

debug('showProject('+fid+','+pid+','+refresh+','+fileid+','+noteid+')');
var W=getProjectById(pid);
if(W==null)
return floatError('Could not find project (pid='+pid+')');

tree_show(fid,pid);
if(!fileid)fileid=0;
if(!noteid)noteid=0;
setwxpview(fid+'x'+pid+'x'+fileid+'x'+noteid);

var t='projectInfo.',
addPart='';
if(getUserId()==W.ownerid)
addPart='['+iLink('addProjectParticipant('+pid+')','Add')+']';

if(0){
var html=
bold(W.name)+
'<table class=tightT>'+






'<tr>'+
'<td onclick="toggleParticipantList()" class="clickable bold">=&gt;Collaborators ('+W.participants.length+')</td>'+
tdr(addPart)+
'</tr>'+
'<tr><td colspan=2 id=participantsC style="display:none;">'+
'<span id=participants>'+
buildParticipants(W)+
'</span>\n'+

'</td></tr>'+
'</table><br/>'+
'</form>';

}

showNotesTable(pid,null,refresh);
}

function toggleParticipantList(){

var i=gel('participantsi'),
s=gel('participantsC').style;
if(i.className=='imgD'){
s.display='none';
i.className='imgR';
}else{
s.display='';
i.className='imgD';
}
}

function addNote(pid){

if(!isProjectParticipant(pid))
return floatNotice(wtext('addNote.error.notpart'));
var t='addNote.',
html='<textarea wrap=soft id=notetext rows=10 cols=40 onfocus="if(!this.seen)value=\'\';this.seen=true;">'+
wtext(t+'body')+'</textarea><br/>'+
'Chars left: <span id=notetextLen></span>';
floatAsk(wtext(t+'title'),html,
[buttonCancel(),
button(wtext('next'),'addNoteDo('+pid+')')]
);

addNoteWatcher(1);
}

var addNoteWatcher_run=false;
function addNoteWatcher(r){

if(r)addNoteWatcher_run=true;

if(!addNoteWatcher_run)return;

var t=gel('notetext'),
c=gel('notetextLen');
if(!t||!c)return;

checkField(t,null,MAX.note.length);
c.innerHTML=MAX.note.length-t.value.length;
try{t.focus();}catch(e){return;}

setTimeout(addNoteWatcher,100);
}

function addNoteDo(pid){

var n=gel('notetext').value;
if(n.length==0)return floatError(wtext('addNote.error.empty'));

addNoteWatcher_run=false;
floatProgress();

var data='addNote='+pid+
'&notetext='+escape(n)+
'&wxpauth='+wxpauth;

ckajax.getText(base(data),data,function(stat,statStr,resp){
fH();
if(resp.indexOf('Error')!=-1)
return floatError(resp);

showNotesTable(pid,null,true);
});
}

function resortProjectEnable(f){
qImgSet('sort_date','');
qImgSet('sort_from','');
qImgSet('sort_recip','');
qImgSet('sort_subj','');

resortProject_skip=!f;
}

var notes_sort={last:'date',by:'date',rev:1};
var notes=[],epms=[],resortProject_skip;
function resortProject(by){
debug('resortProject('+by+')');
if(resortProject_skip)
return;
var V=getwxpview().split('x');
if(V[1]==0)return;
notes_sort={
last:notes_sort.by,
by:by,
rev:(notes_sort.rev ^ (notes_sort.by==by?1:0))
};
showNotesTable(V[1]);
}
function showNotesTable(pid,refresh){

wxpLoading('emailDIV');

var W=getProjectById(pid),
get=refresh?ckajax.getText:ckajax.getCached,
data='getProjectNotes='+pid+
'&wxpauth='+wxpauth;

if(pid <0){
notes=[];
for(var i=0;i<files.length;i++){
if(files[i].projectid!=pid)
continue;

notes[notes.length]={id:i,type:files[i].type=='email'?'EMAIL':'UPLOAD',userid:files[i].userid,fileid:files[i].id,text:b64dec('RW1haWwgYXJyaXZlZA..')};
}
return showNotesTable2(pid,W.notes=notes);
}

get(base(data),data,function(stat,statStr,resp){
if(stat!=200)
return floatError('Server unavilable,check connection and try again. (Status: '+stat+')');
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
var R=parseResponse(resp),
nu=R.newUser,
d=new Date();
for(var i=0;i<nu.length;i++){
if(nu[i].removed==0xffffff){
addUserToProject(nu[i],pid);
}else{
addUser(nu[i]);
}
}
notes=R.notes;
epms=R.epms;

for(var i=0;i<notes.length;i++)
notes[i].text=b64dec(notes[i].text);

if(R.currentTime)
currentTimeDelta=Math.floor(d.getTime()/1000)-tzOffset()-R.currentTime;

if(R.files)
for(var i=0;i<R.files.length;i++)
addFileToMemory(R.files[i]);

if(R.subsidies)
subsidies=R.subsidies;

if(R.rules){
for(var i=0;i<R.rules.length;i++){
var r=R.rules[i];
r.tccindex=b64dec(r.tccindex);
r.fromrule=b64dec(r.fromrule);
r.ipaddrrule=b64dec(r.ipaddrrule);
}
}

try{
showNotesTable2(pid,W.notes=notes);
}catch(e){
floatError(e);
}
});
}

function genNotesTableRows(notes,search){
debug('genNotesTableRows(len='+notes.length+','+search+')');
var html='';

for(var i=0;i<notes.length;i++){
var fcn=null,fcns='noop',
n=notes[i],
F=getFileById(n.fileid),
idx,
t=n.text;



if(n.fileid!=0&&F==null){
if(search){
continue;
}else{
debug('reloading showProject()');
return tree_loadData(function(){showProject(getProjectById(n.projectid).folderid,n.projectid);});
}
}

if(n.type=='ADDPART'||n.type=='DELPART'){
continue;





}
if(n.type=='NEWEMAIL'){
var tok=' changed address to ',
a=t.split(tok);
t='C'+tok.substring(2)+bold(showParticipant(getUserByEmail(a[1])));
}
else if(n.type=='USERNOTE'){
fcns='showFullNote';
fcn=showFullNote;
notes[i].expandFcn=fcn;
}
else if(n.type=='RENAME'||n.type=='CREATE'){
continue;
fcns='showFullNote';
fcn=showFullNote;
t=t.substring(0,idx=t.indexOf(': '))+': '+bold(t.substring(idx+2));


if((idx=t.indexOf(':'))!=-1)
t=t.substr(0,idx+2)+bold(t.substr(idx+2));
else if((idx=t.indexOf(' \''))!=-1)
t=t.substr(0,idx)+': '+bold(t.substring(idx+2,t.length-1));
notes[i].expandFcn=fcn;
}

if(F){
if(n.type=='CHECKEPM'){
t=t+': '+F.name;
t=t.substr(0,idx=t.indexOf(':'))+': '+bold(t.substr(idx+2));
fcns='uspsVerifyPostmark';
fcn=uspsVerifyPostmark;
}
else if(typeIsFile(n)){
t=t+': '+F.name;
idx=t.indexOf(':');

t=bold(t.substring(idx+2));
fcns='showFile';
fcn=showFile;
}
else if(n.type=='DOWNLOAD'||n.type=='LISTEN'||n.type=='EMAILDL'){
idx=t.indexOf(' ');
if(t.indexOf('@')!=-1&&t.indexOf('@')<idx){
t=t.substring(idx+1);
t=t.substring(0,1).toUpperCase()+t.substring(1);
}
idx=t.indexOf(':');
t=t.substring(0,idx)+': '+bold(t.substring(idx+2));
fcns='showFile';
fcn=showFile;
}
notes[i].expandFcn=fcn;
}

n=notes[i];


var exp='toggleNote('+i+','+fcns+','+n.fileid+','+n.sequence+')',
clk='if(toggleNoteIsClosed('+i+'))'+exp+'',
from=parseEmail(F.from),
recip='&nbsp;';
from=floatText(getInitials(from),showEmail(from));

if(F){
var T=F.to.split(';'),
C=F.cc.split(';');
if(F.to.length==0)T=[];
if(F.cc.length==0)C=[];
if((T.length+C.length)==0){
recip='&nbsp;';
}else if((T.length+C.length)==1){
if(T.length==1){
recip=floatEmail(parseEmail(T[0]),26);
}else{
recip=floatEmail(parseEmail(C[0]),26);
}
}else{
var to='&nbsp;',len=26-3;
if((T.length+C.length)>9)len--;
if(C.length!=0)to=C[0];
if(T.length!=0)to=T[0];
recip=floatEmail(parseEmail(to),len)+'&nbsp;+'+(T.length+C.length-1);
}
}

var plusminus='<table class=tight><tr><td style="padding:0px"><img src=i/1.gif height=3 width=1 /></td></tr><tr><td id=notei'+i+' style="padding:0px;cursor:pointer;background:#ffffff url(i/wxpall.png) no-repeat -544px -216px"><img width=11 height=11 src=i/1.gif /></td></tr></table>';
if(search){
plusminus='';
exp=clk='showProject('+getProjectById(n.projectid).folderid+','+n.projectid+',false,'+n.fileid+')';
}
html+=qTrjs({

sty:'cursor:pointer;'+(n.userid==getUserId()?'color:#0000ff': ''),
id:'noteRow'+i
},
(search?td(S(28)):tdnote(iCheck('notec'+i,'val',null,'this.checked^=1'),'noteCheckClick('+i+')'))+

tdnote('<table class=tight><tr><td style="padding:0px;vertical-align:top">'+plusminus+'</td><td style="padding:0px" id=noted'+i+'>&nbsp;'+floatTime(F?F.postmarkdate:n.date)+'</td></tr></table>',clk)+
tdnote(from,clk,'notefrom'+i)+
tdnote(recip,clk,'noteto'+i,1)+
tdnote(floatTruncText(t,45),clk,'note'+i)
);
}

return html;
}

function noteCheckClick(nid){
var c;
gel('notec'+nid).checked ^=1;
for(var i=0;i<10000;i++){
if(!(c=gel('notec'+i)))
return gel('fileaction').disabled=1;
if(c.checked)
return gel('fileaction').disabled=0;
}
}

function showNotesTable2(pid,notes){

var W=getProjectById(pid);

qImgSet('sort_'+notes_sort.last,'');

debug('showNotesTable2 sort='+notes_sort.by+' rev='+notes_sort.rev);
qImgSet('sort_'+notes_sort.by,notes_sort.rev?'down':'up');




var t='projectlog.header.',
html='<table class=pad id=noteTable>';

quicksort(notes,showNotesTable_cmp);
if(notes_sort.rev)
notes=notes.reverse();

qTrN=0;qTrBg=['#ffffff','#f2f2f2'];

html+=genNotesTableRows(notes)+
'<tr>'+
tdS(1)+
tdS(91)+
tdS(43)+
tdS(191)+
tdS(302)+
'</tr>'+
'</table>';

if(W==recipProject){
html+=wtext('thisisRecipEmail.html',{PID:pid});
}else{
html+=wtext('thisisProject.html',{PID:pid,NAME:W.name});
}

gel('emailDIV').innerHTML=html;

if(showProject_newest)
showProject_newest=false;


var fw=getwxpview().split('x');
fw[3]*=1;
debug('note view='+getwxpview());
if(fw.length>=3){
for(var i=0;i<notes.length;i++){
var n=notes[i];
if(fw[3]){
if(n.id==fw[3]){
var n=gel('note'+i);
if(n){
gel('emailDIV').scrollTop=gel('noteRow'+i).offsetTop;
n.onclick();
}
}
}
else if(fw[2]!=0&&n.fileid==fw[2]){
var n=gel('note'+i);
if(n){
gel('emailDIV').scrollTop=gel('noteRow'+i).offsetTop;
n.onclick();
}
}
}
}

}

function checkAllNotes(A){
if(getwxpview().split('x')[1]==0)return gel('checkall').checked=false;
gel('fileaction').disabled=!A.checked;
for(var i=0;i<10000;i++){
var C=gel('notec'+i);
if(!C)break;
C.checked=A.checked;
}
}


function toggleNoteIsClosed(id){
var r=gel('noteRow'+id),
now=gmtime();
debug('noteRowToggle open='+r.open);
if(r.open)
return false;
return r.last!=now;
}

function typeIsFile(n){

return n.type=='EMAIL'||n.type=='UPLOAD'||n.type=='NOTESCAP';
}


function noteShowHideAll(len){

var expN=0;

for(var i=0;i<len;i++){
if(gel('notei'+i).expanded)
expN++;
}

for(var i=0;i<len;i++){


if(expN!=0){
if(gel('notei'+i).expanded){
toggleNote(i,notes[i].expandFcn,notes[i].fileid,notes[i].sequence);
}
}
else{
toggleNote(i,notes[i].expandFcn,notes[i].fileid,notes[i].sequence);
}
}
fH();
}


function toggleNote(nid,callback,fid,seq){
debug('toggleNote('+nid+','+callback+','+fid+','+seq+')');

var v=getwxpview().split('x');
setwxpview(v[0]+'x'+v[1]+'x'+fid+'x'+notes[nid].id);


var n=gel('note'+nid),
t=gel('noteto'+nid),
f=gel('notefrom'+nid),
d=gel('noted'+nid),
r=gel('noteRow'+nid);
r.last=gmtime();

gel('notei'+nid).onclick=function(){toggleNote(nid,callback,fid,seq);};

if(n.savedHTML){

if(!r.open){
n.innerHTML=n.savedHTML;
f.innerHTML=f.savedHTML;
t.innerHTML=t.savedHTML;
d.innerHTML=d.savedHTML;
qImgSet('notei'+nid,'minus');
toggleNoteRelated(nid,fid,true);
r.open=true;
r.style.cursor='default';
}else{
n.innerHTML=n.innerHTMLPre;
f.innerHTML=f.innerHTMLPre;
t.innerHTML=t.innerHTMLPre;
d.innerHTML=d.innerHTMLPre;
qImgSet('notei'+nid,'plus');
gel('notei'+nid).onclick=noop;
toggleNoteRelated(nid,fid,false);
r.open=false;
r.style.cursor='pointer';
var V=getwxpview().split('x');
setwxpview(V[0]+'x'+V[1]+'x0x0');
}
var C=r.childNodes;


return;
}

var C=r.childNodes;
for(var j=0;j<C.length;j++)
C[j].style.verticalAlign='top';
r.style.cursor='default';



n.savedHTML=n.innerHTMLPre=n.innerHTML;

d.innerHTMLPre=d.innerHTML;
var F=getFileById(notes[nid].fileid);
datehtml='<br/>'+floatTimeFull(notes[nid].date,null,1);
if(F&&F.postmarkdate)
datehtml='&nbsp;Postmark:<br/>'+floatTimeFull(F.postmarkdate,null,1);
d.innerHTML=d.savedHTML=datehtml;

qImgSet('notei'+nid,'minus');
toggleNoteRelated(nid,fid,true);


f.innerHTMLPre=f.innerHTML;
f.innerHTML=f.savedHTML=f.innerHTML;


t.innerHTMLPre=t.innerHTML;
var recips='';
if(notes[nid].fileid){
var F=getFileById(notes[nid].fileid);
if(F){
T=F.to.split(';');
if(F.to.length!=0&&T.length!=0){
for(var i=0;i<T.length;i++){
recips+=floatEmail(parseEmail(T[i]),26)+'<br/>';
}
}

C=F.cc.split(';');
if(F.cc.length!=0&&C.length!=0){
recips+='<br/>Cc:<br/>';
for(var i=0;i<C.length;i++){
recips+=floatEmail(parseEmail(C[i]),26)+'<br/>';
}
}
}
}
t.innerHTML=t.savedHTML=recips;

r.open=true;
debug('noteRow open='+r.open);

if(callback)
callback(nid,fid,seq);
}

function toggleNoteRelated(nid,fid,show){

var N=notes[nid];

if(N&&N.backmap){
N=N.backmap;
for(var i=0;i<N.length;i++){

if(N[i]!=''&&N[i]!=nid){
gel('noteRow'+N[i]).style.display=show?'':'none';
}
}
}
}


function noteRowOver(r){

r.onmouseout=function(){noteRowOut(r);};
var d=r.childNodes;
for(var i=0,n=0;i<d.length;i++){
if(!d[i].innerHTML)
continue;
var add=(d[i].className.indexOf('clickable')!=-1)?' clickable':'';
d[i].oldbackgroundColor=d[i].style.backgroundColor;
d[i].style.backgroundColor='#D8DDF2';
}
}


function noteRowOut(r){

var d=r.childNodes;
for(var i=0,n=0;i<d.length;i++){
if(!d[i].innerHTML)
continue;
var add=(d[i].className.indexOf('clickable')!=-1)?' clickable':'';
d[i].style.backgroundColor=d[i].oldbackgroundColor;
}
}

function noop(){return false;}


function showFileJump(fid){
fid *=1;
for(var i=0;i<files.length;i++){
if(files[i].id==fid){
var P=getProjectById(files[i].projectid);
if(!P)P=recipProject;
showProject(P.folderid,P.id,false,fid,0);
}
}
}


function showFile(dest,id){

var F=getFileById(id);
if(F==null)
return floatError('File not loaded id='+id);

if(isMp3File(F.name)){
var e=gel('note'+dest),
data='getMp3Tags='+id;
e.innerHTML=wtext('loading.fill');
ckajax.getCached(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
showFile2(dest,id,F,{mp3:parseResponse(resp)});
});
}
else if(F.type==FILETYPE.EMAIL){
var e=gel('note'+dest),
data='getEmailInfo='+id
+'&wxpauth='+wxpauth;
e.innerHTML=wtext('loading.fill');
ckajax.getCached(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
showFile2(dest,id,F,{email:parseResponse(resp)});
});
}
else{
showFile2(dest,id,F,null);
}
}
function showFile2(dest,id,F,R){

qTrBg=['{QTRBGN}','{QTRBGN}'];qTrN=0;
var more='',
rnd=Math.floor(1e7*Math.random()),
e=gel('note'+dest);

if(!e)return;

if(R&&R.mp3){
more+=
qTrh('File Name',floatTruncText(F.name,24))+
qTrh('Size',humanSize(F.size,true))+
showMp3Tags(R.mp3)+
qTrh('Listen',qimg('Music','j:playSong('+id+')','player'+id))+
qTrh('Download','<a target="_new'+rnd+'" href="'+downloadFileURL(id)+'">'+wtext('showFile.download')+'</a>');
}
else if(R&&R.email){
var R=R.email;
more+=
showEmailInfo(R,F)+
qTrh('Size',humanSize(F.size,true))+

'';
if(R.att)
more+=qTrh('Attachments',fixWidth(showFileAttachments(R.att)));
}
else{
more+=
qTrh('File Name',floatTruncText(F.name,24))+
qTrh('Size',humanSize(F.size,true));
}

var E=getEpmByFileId(F.id),
html='';
if(E){
t='epmInfo.';

html=
wtext(t+'wxp.body',{
MORETR:more,
WXPNAME:SYSINFO.name,
WXPAPPURL:SYSINFO.appurl,
ID:id,
FILEID:F.id,
ID:id,
FILEHASH:b64hex(F.filehash),
EPMDATE:floatTimeFull(F.postmarkdate),
EPMTRANKEY:F.epmtrankey,
DLFILEURL:downloadFileURL(id),
DLDISP:(getFileById(id).type==FILETYPE.OTHER?'':'display:none')
});
html=parseCounter(strReplace(html,'{QTRBGN}','{QTRBG{**N:2}}'));
html=parseTmpl(html,{QTRBG0:'#ffffff',QTRBG1:'#f2f2f2'});
}

e.innerHTML=e.savedHTML=html+'</table>';
}
function showFileAttachments(att){

var ret='';
for(var i=0;i<att.length;i++){
if(att[i].name=='')
att[i].name='<i>none</i>';

ret+=floatTruncText(att[i].name+'['+humanSize(att[i].size)+']',28)+'<br/>\n';
}
return ret;
}
function getFileIcon(t){

if(FILEICON[t])
return FILEICON[t];

return FILEICON.other;
}

function sendEmailDownload(id){

var data='sendEmailDownload='+id+
'&wxpauth='+wxpauth,
t='sendEmailDownload.';
floatProgress();

ckajax.getText(base(data),data,function(stat,statStr,resp){
fH();
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
sendEmailDownloadConfirm(id);
});
}
function sendEmailDownloadConfirm(id){

var t='sendEmailDownloadConfirm.';
floatAsk(wtext(t+'title'),
wtext(t+'body',{TITLE:getFileById(id).name,EMAIL:wxpemail}),
[button(wtext('close'),'fH()')]
);
}

function downloadFileURL(id){

var F=getFileById(id);
return APP+'/'+escape(F.name)+'?wxpauth='+wxpauth+'&downloadFile='+id;
}

function showMp3Tags(R){

var T=R.mp3tags[0],
html=
qTrh('Title',T.title)+
qTrh('Track',T.tracknumber)+
qTrh('Album',T.album)+
qTrh('Artist',T.artist)+
qTrh('Year',T.year)+
qTrh('Bitrate',T.bitrate+'Kbps')+
qTrh('Frequency',T.frequency+'KHz');
return html;
}


function showEmailInfo(R,F){

var I=R.emailinfo[0];









var A=I.from.split('|'),
html=
qTrh('Subject',floatTruncText(nobr(safeHTML(b64dec(I.subject))),34));






return html;
}


function showEmailRules(R){

var S=subsidies,
html='<table class=pad2>';
for(var i=0;S&&i<S.length;i++){
var r=S[i],
exp=1*r.created+1*r.duration;
if(r.threadid!=R.emailinfo[0].threadid)
continue;
html+=
qTr(bold('Type'),r.type)+
qTr(bold('Remaining'),(r.quantity-r.consumed)+' / '+r.quantity)+
qTr(bold('Created'),floatTime(r.created))+
qTr(bold('Expires'),floatTime(exp,true));
}
return html+'</table>';
}

var playSongLast=null;
function playSong(id){

if(playSongLast){
var p=playSongLast;
p.innerHTML=p.savedHTML;
p.onclick='playSong('+p.id+')';
p.className='clickable';
}


var p=playSongLast=gel('player'+id),
vars='mp3='+escape(downloadFileURL(id)+'&listen=1')+
strReplace(',autoplay=1,volume=50,showstop=0,showinfo=1,showvolume=1,showloading=always,sliderwidth=10',',','&amp;'),
html=
'<object class="playerpreview" type="application/x-shockwave-flash" '+
'data="i/player_mp3_maxi.swf" width=1 height=1>'+
'<param name="movie" value="i/player_mp3_maxi.swf" />'+
'<param name="FlashVars" value="'+vars+'" />'+
'<param name="wmode" value="transparent" />'+
'<embed src="i/player_mp3_maxi.swf" type="application/x-shockwave-flash" width=1 height=1 '+
'flashvars='+vars+'></embed>'+
'</object>Playing...';
p.savedHTML=p.innerHTML;
p.innerHTML=html;
p.onclick='';
p.className='';
}

function remoteVerifyAsk(dest,id){

var left=SYSINFO.epmperfile-getFileById(id).remoteVerifyCount,
t='remoteVerify.',
suff=wtext(t+'verifyButtonSuffix');
floatAsk(wtext(t+'title'),
wtext(t+'body',{WXPNAME:SYSINFO.name,EPMPERFILE:SYSINFO.epmperfile,VERLEFT:left}),
[button(wtext('cancel'),'gel(\'note'+dest+'\').savedHTML=\'\'; floatHide()'),
button(SYSINFO.name+suff,'wxpVerifyPostmark('+dest+','+id+')'),
button(wtext(t+'uspsVerify'),'uspsVerifyPostmark('+dest+','+id+',null)')]
);
}

function wxpVerifyPostmark(dest,id,fcn){

var el=gel('note'+dest),
F=getFileById(id);


if(dest){
el.pointer='progress';
el.innerHTML=wtext('loading');
}

var data='wxpVerifyPostmark='+id+
'&wxpauth='+wxpauth;
ckajax.getCached(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
qTrBg=['#ffffff','#f2f2f2'];qTrN=0;
var R=parseResponse(resp),
T={WXPNAME:SYSINFO.name,
WXPAPPURL:SYSINFO.appurl,
ID:id,
DATE:floatTimeFull(R['epmcheckdate'][0][0])},
rnd=Math.floor(1e7*Math.random()),
t='epmInfo.',
dlhtml=getFileById(id).type==FILETYPE.EMAIL
? ('['+iLink('sendEmailDownload('+id+')',wtext('showFile.sendEmailDownload'))+']')
: ('[<a target=_newfile'+rnd+' href="'+downloadFileURL(id)+'">'+wtext(t+'downloadOriginalFile')+'</a>]'),
html=
wtext(t+'wxp.body',T)+
'<table class=pad2 width=100%>\n'+
qTrh(wtext(t+'fileName'),F.name)+
qTrh(wtext(t+'fileTime'),floatTimeFull(R['file.modtime'][0][0]))+
qTrh(wtext(t+'fileHash'),fixWidth(b64hex(R['file.hash'][0][0])))+
qTrh(wtext(t+'epmTime'),floatTimeFull(R['epm.utctime'][0][0]))+
qTrh(wtext(t+'epmTrankey'),fixWidth(R['epm.trankey'][0][0])+
'<br/>[<a target=_newepm'+rnd+' href="'+SYSINFO['appurl']+'?showEpmHtml='+R['epm.trankey']+'&download=1">'+wtext(t+'download')+'</a>&nbsp;|'+
iLink('resendEpmEmail(\''+R['epm.trankey']+'\')',wtext(t+'resend'))+'&nbsp|'+
' <a target=_newepm'+rnd+' href="'+SYSINFO['appurl']+'?showEpmHtml='+R['epm.trankey']+'&print=1">'+wtext(t+'print')+'</a>]<br/>'+
dlhtml)+
'</table>';

if(dest){
el.innerHTML=el.savedHTML=html;
}else{
fcn(html);
}
});
}

function resendEpmEmail(epmtrankey){

var data='resendEpmEmail='+epmtrankey+
'&wxpauth='+wxpauth;
floatProgress();
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error: ')!=-1)
return floatError(resp);
var t='epmInfo.resend.done.';
floatAsk(wtext(t+'title'),
wtext(t+'body',{EMAIL:wxpemail}),
[button(wtext('close'),'fH()')]
);
});
}

function uspsVerifyPostmark(dest,id,seq){

var el=gel('note'+dest),
F=getFileById(id),
t='epmInfo.';

fH();

if(seq==null){
el.innerHTML=wtext(t+'callingUSPS');
seq='';
}else{
el.pointer='progress';
el.innerHTML=wtext('loading');
seq='&sequence='+seq;
}

var data='uspsVerifyPostmark='+id+
seq+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
fH();

if(resp.indexOf('Error:')!=-1)
return floatError(resp);

var R=parseResponse(resp),
html=bold(wtext(t+'usps.title'))+'<br/>\n'+
wtext(t+'usps.body',{DATE:floatTimeFull(R['epmcheckdate'][0])})+
'<table class=cleanT>\n'+
qTr(wtext(t+'fileName'),F.name)+
qTr(wtext(t+'fileTime'),floatTimeFull(R['file.modtime'][0]))+
qTr(wtext(t+'fileHash'),fixWidth(b64hex(R['file.hash'][0][0])))+

qTr(wtext(t+'sigHash'),fixWidth(b64hex(R['sig.hash'][0][0])))+
qTr(wtext(t+'sigTime'),floatTimeFull(utc(R['sig.utctime'][0][0])))+

qTr(bold(wtext(t+'epmTime')),floatTimeFull(utc(R['epm.utctime'][0][0])))+
qTr(bold(wtext(t+'epmTrankey')),fixWidth(R['epm.trankey'])+qimg('UspsEpmBut'))+
qTr(bold(wtext(t+'statusCode')),fixWidth(R['usps.statusCode']))+
qTr(bold(wtext(t+'statusMessage')),fixWidth(R['usps.statusMessage']))+
'</table>';

getFileById(id).remoteVerifyCount--;
el.innerHTML=el.savedHTML=html;
});
}

function showFullNote(i){

var t=notes[i].text,
e=gel('note'+i);
t=strReplace(t,'>','&amp;gt;');
t=strReplace(t,'<','&amp;lt;');
t=strReplace(t,'\n','<br/>');
e.style.whiteSpace='normal';
e.innerHTML=e.savedHTML=t;
}

function showNotesTable_cmp(a,b){
var s=notes_sort.by;
if(s=='Type'){
a=a.type;
b=b.type;
}
if(s=='from'){
if(a.userid)a=getUserById(a.userid).email;
else{
if(!a.fileid)return-1;
a=parseEmail(getFileById(a.fileid).from).addr;
}
if(b.userid)b=getUserById(b.userid).email;
else{
if(!b.fileid)return-1;
b=parseEmail(getFileById(b.fileid).from).addr;
}
}
if(s=='recip'){
if(!a.fileid)return-1;
a=getFileById(a.fileid);
if(!a)return-1;
a=parseEmail(a.to).addr;
if(!b.fileid)return 1;
b=getFileById(b.fileid);
if(!b)return 1;
b=parseEmail(b.to).addr;
}
if(s=='subj'){
a=a.text.toLowerCase()+(typeIsFile(a)?getFileNameById(a.fileid):'');
b=b.text.toLowerCase()+(typeIsFile(b)?getFileNameById(b.fileid):'');

}
if(a==null)return-1;
if(b==null)return 1;
if(s=='date'){
if(a.fileid*1&&1*b.fileid){


a=getFileById(a.fileid);
b=getFileById(b.fileid);
if(!a)return-1;
if(!b)return 1;
return a.postmarkdate-b.postmarkdate;
}
return a.date-b.date;
}else{
var prev='a='+a+' b='+b;
try{

return a<b?-1:(a>b?1:0);
}catch(e){
a=typeof a;
b=typeof b;
if(a==b)
return 0;
if(a=='unknown')
return-1;
if(b=='unknown')
return 1;

debug('NOTE SORT ERROR: prev:'+prev+'; now:a='+a+' b='+b+' err:'+e.message);
return 0;
}
}
}

function name_cmp(a,b){
a=a.name;b=b.name;
a=b64dec(a).toLowerCase();
b=b64dec(b).toLowerCase();
if(typeof a=='unknown')a='';
if(typeof b=='unknown')b='';
if(a==b)return 0;
if(a==toBeFiled.toLowerCase())return-1;
if(b==toBeFiled.toLowerCase())return 1;
if(a.charAt(0)=='_'&&b.charAt(0)!='_')return-1;
if(a.charAt(0)!='_'&&b.charAt(0)=='_')return 1;
try{
return a<b?-1:1;
}catch(e){
alert('Ex:'+e+'\n'+e.message+'\na='+(typeof a)+' b='+(typeof b));
}
}

function buildParticipants(E){

var html='<table class=tightT>',
p=E.participants;

for(var i=0;i<p.length;i++){
var u=getUserById(p[i]),
del='',
cls='class=mine';
if(wxpemail!=u.email){
cls='';
if(E.ownerid==null){
del=delFolderParticipantImg(u.email,E.id);
}else if(getUserId()==E.ownerid){
del=delProjectParticipantImg(u.email,E.id);
}
}
html+='<tr '+cls+'><td>('+getInitials(u)+')</td><td>'+showParticipant(u)+'</td><td>'+del+'</td></tr>\n';
}
return html+'</table>';
}

function addProjectParticipant(pid){

addProjectParticipant.pid=pid;
if(wxptrial)
return showTrialAddPart();

var W=getProjectById(pid),
t='addParticipant.project.',
html=iForm('addProjectParticipantDo('+pid+')')+
wtext(t+'body',{PROJECT:W.name})+
'</form>';
floatAsk(wtext(t+'title'),html,
[buttonCancel(),
button(wtext('next'),'addProjectParticipantDo()')]
);
gel('newPart').focus();
}

function addProjectParticipantDo(){

fH();

var pid=addProjectParticipant.pid,
p=gel('newPart').value;
if(p=='')
return;

var back='addProjectParticipant('+pid+')',
data='addProjectParticipant='+p+
'&pid='+pid+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error: Trial User')!=-1)
return floatNotice(wtext('addParticipant.trialUser'),back);
if(resp.indexOf('Error: User not verified')!=-1)
return floatNotice(wtext('addParticipant.folder.notVerified'),back);
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
if(resp.indexOf('Ask:')!=-1)
return addParticipantNotFound(p,-1,pid);

var R=parseResponse(resp),
nuser=R.newUser[0],
W=getProjectById(pid);
addUserToProject(nuser,pid);

gel('participants').innerHTML+='<li>'+showUser(getUserByEmail(p))+delProjectParticipantImg(p,pid);
gel('newPart').value='';

showProject(W.folderid,pid,true);
});
}

function delProjectParticipantImg(email,pid){

fLink++;
return S(16)+'<br/><a id=fLink'+fLink+' onmouseover="floatNearShow('+fLink+',\'Remove\')" '+
'href="#" onclick="delProjectParticipant(\''+email+'\','+pid+');return false">[-]</a>';
}

function delProjectParticipant(email,pid){

var t='delProjectParticipant.';
floatAsk(wtext(t+'title'),
wtext(t+'body',{EMAIL:email,PROJECTNAME:getProjectById(pid).name}),
[buttonCancel(),
button(wtext('next'),'delProjectParticipantAsk2(\''+email+'\','+pid+')')]
);
}

function delProjectParticipantAsk2(email,pid){

var t='delProjectParticipant.ask2.';
floatAsk(wtext(t+'title'),
wtext(t+'body',{EMAIL:email,PROJECTNAME:getProjectById(pid).name}),
[buttonCancel(),
button(wtext('next'),'delProjectParticipantDo(\''+email+'\','+pid+')')]
);
}

function delProjectParticipantDo(email,pid){

fH();
var data='delProjectParticipant='+email+
'&pid='+pid+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error:')!=-1)
return floatError(resp);

var R=parseResponse(resp),
W=getProjectById(pid);
delUserFromProject(R.userid,pid);

gel('participants').innerHTML=buildParticipants(getProjectById(pid));

showProject(W.folderid,pid,true);
});
}

function addFolderParticipant(fid){

if(wxptrial)
return showTrialAddPart();

var F=getFolderById(fid),
replace={
FOLDER:F.name,
FOLDERLIST:getSubFolderList(F),
PROJECTLIST:getSubProjectList(F)},
t='addParticipant.folder.',
html=iForm('addFolderParticipantDo('+fid+')')+
wtext(t+'body',replace)+'</td></tr>'+
'</form>';
floatAsk(wtext(t+'title'),html,
[buttonCancel(),
button()]
);
setTimeout("gel('newPart').focus();",250);
}

function addFolderParticipantDo(fid){

fH();

var p=gel('newPart').value;
if(p=='')
return;









var back='addFolderParticipant('+pid+')',
data='addFolderParticipant='+p+
'&fid='+fid+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error: Trial User')!=-1)
return floatNotice(wtext('addParticipant.trialUser'),back);
if(resp.indexOf('Error: User not verified')!=-1)
return floatNotice(wtext('addParticipant.folder.notVerified'),back);
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
if(resp.indexOf('Ask:')!=-1)
return addParticipantNotFound(p,fid,-1);

tree_loadData(function(){
showFolder(fid);
});
});
}

function delFolderParticipantImg(email,fid){

fLink++;
return S(16)+'<br/><a id=fLink'+fLink+' onmouseover="floatNearShow('+fLink+',\'Remove\')" '+
'href="#" onclick="delFolderParticipant(\''+email+'\','+fid+');return false">[-]</a>';
}

function delFolderParticipant(email,fid){

var F=getFolderById(fid),
replace={
EMAIL:email,
FOLDERNAME:F.name,
FOLDERLIST:getSubFolderList(F),
PROJECTLIST:getSubProjectList(F)},
t='delFolderParticipant.';
floatAsk(wtext(t+'title'),
wtext(t+'body',replace),
[buttonCancel(),
button(wtext('next'),'delFolderParticipantAsk2(\''+email+'\','+fid+')')]
);
}

function delFolderParticipantAsk2(email,fid){

var F=getFolderById(fid),
replace={
EMAIL:email,
FOLDERNAME:F.name,
FOLDERLIST:getSubFolderList(F),
PROJECTLIST:getSubProjectList(F)},
t='delFolderParticipant.ask2.';
floatAsk(wtext(t+'title'),
wtext(t+'body',replace),
[buttonCancel(),
button(wtext('next'),'delFolderParticipantDo(\''+email+'\','+fid+')')]
);
}

function delFolderParticipantDo(email,fid){

fH();
var data='delFolderParticipant='+email+
'&fid='+fid+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error:')!=-1)
return floatError(resp);

tree_loadData(function(){
showFolder(fid);
});
});
}

function addParticipantNotFound(email,fid,pid){

var t='addParticipant.notFound.';
floatAsk(wtext(t+'title'),
wtext(t+'body',{EMAIL:email}),
[buttonCancel(),
button(wtext('next'),'addParticipantInvite(\''+email+'\','+fid+','+pid+')')]
);
}

function addParticipantInvite(email,fid,pid){

fH();
var t='addParticipant.notFound.invite.',
msg=gel('inviteMsg'),
html=wtext(t+'body',{EMAIL:email,FID:fid,PID:pid})+
'<table class=tightT>'+
qTr(wtext(t+'from'),SYSINFO.name)+
qTr(wtext(t+'to'),email)+
qTr(wtext(t+'subject')+'&nbsp;','Invite from '+wxpemail)+
'<tr><td colspan=2><textarea wrap=soft id=inviteMsg rows=10 cols=60 onfocus="if(!this.seen)this.value=\'\';this.seen=1;">'+
(msg==null?wtext(t+'message',{EMAIL:email}):msg.value)+
'</textarea><br/>'+
'Chars left: <span id=inviteMsgLen></span>'+
'</td></tr>'+
'</table></form>';
floatAsk(wtext(t+'title'),html,
[buttonCancel(),
button(wtext('next'),'addParticipantInviteDo(\''+email+'\','+fid+','+pid+')')]
);

addParticipantInviteWatcher();
}

function addParticipantInviteWatcher(){

var t=gel('inviteMsg'),
c=gel('inviteMsgLen');
if(!t||!c)
return;

checkField(t,null,MAX.invite.msgLength);
c.innerHTML=MAX.invite.msgLength-t.value.length;
try{
t.focus();
}catch(e){
return;
}

setTimeout(addParticipantInviteWatcher,100);
}


function addParticipantInviteDo(email,fid,pid){

var msg=gel('inviteMsg').value;
if(msg.length==0){
var t='addParticipant.notFound.noMsg.';
return floatAsk(wtext(t+'title'),
wtext(t+'body'),
[button(wtext('back'),'fH();addParticipantInvite(\''+email+'\','+fid+','+pid+');')],
2);
}

fH();
var data='sendInvite='+escape(email)+
'&fid='+fid+
'&pid='+pid+
'&msg='+escape(msg)+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
floatDone(wtext('addParticipant.notFound.invite.done',{EMAIL:email}));
if(fid==-1){

addUserToProject({name:'V2FpdGluZyB0byBTaWdudXA=',email:email,id:resp},pid);
showProject(getProjectById(pid).folderid,pid,true);
}else{
addUserToFolder({name:'V2FpdGluZyB0byBTaWdudXA=',email:email,id:resp},fid);
showFolder(fid);
}
});
}

function delProject(pid){
if(pid <0)
return floatError('Cannot delete '+getProjectById(pid));

var t='delProject.',
W=getProjectById(pid),
sub=countFiles(pid);
if(sub!=0){
return floatAsk(wtext(t+'empty.title'),
wtext(t+'empty.body',{PROJECTNAME:W.name}),
[buttonCancel()]
);
}
floatAsk(wtext(t+'title'),
wtext(t+'body',{PROJECTNAME:W.name}),
[buttonCancel(),
button(wtext(t+'delete'),'delProjectDo('+pid+')')]
);
}
function delProjectDo(pid){

floatProgress();
var fid=getProjectById(pid).folderid,
data='removeProject='+pid+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statstr,resp){
fH();
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
tree_loadData(function(){
showFolder(fid);
});
});
}

function renameProject(pid,fcn){
fC();
renameProject.pid=pid;
renameProject.callback=fcn;

if(pid==recipProject.id)
return floatNotice('Cannot rename '+bold(recipProject.name));
if(pid <0)
return floatNotice('Cannot rename '+bold(getProjectById(pid).name));

var t='renameProject.';
floatAsk(wtext(t+'title'),
wtext(t+'body',{PID:pid,WNAME:getProjectById(pid).name}),
[buttonCancel(),button(wtext('next'),'renameProjectDo()')]
);
gel('addProjectName').focus();
}
function renameProjectDo(){
var pid=renameProject.pid,
name=gel('addProjectName').value;



if(getProjectByName(name,getProjectById(pid).folderid))
return gel('renameProject_msg').innerHTML=wtext('renameProject.samename');

floatProgress();
var data='renameProject='+pid+
'&name='+escape(name)+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statstr,resp){
fH();
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
tree_loadData(function(){
showProject(getProjectById(pid).folderid,pid,true);
if(renameProject.callback)renameProject.callback();
});
gel('emailDIV').innerHTML='';
});
}

function delFolder(fid){

var t='delFolder.',
F=getFolderById(fid),
sub=countSubItems(fid);
if(sub!=0){
return floatAsk(wtext(t+'empty.title'),
wtext(t+'empty.body',{FOLDERNAME:F.name}),
[buttonCancel()]
);
}
floatAsk(wtext(t+'title'),
wtext(t+'body',{FOLDERNAME:F.name}),
[button(wtext('cancel'),'fH()'),
button(wtext(t+'delete'),'delFolderDo('+fid+')')]
);
}
function delFolderDo(fid){

floatProgress();
var pfid=getFolderById(fid).parentid,
pfid=getFolderById(fid).parentid,
data='removeFolder='+fid+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statstr,resp){
fH();
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
tree_loadData(function (){
showFolder(pfid);
});
});
}

function renameFolder(fid,fcn){
fH();
renameFolder.fid=fid;
renameFolder.callback=fcn;

if(fid==topFolder.id)
return floatNotice('Cannot rename '+bold(topFolder.name));
if(fid==sharedFolder.id)
return floatNotice('Cannot rename '+bold(sharedFolder.name));
var F=getFolderById(fid);
if(F&&F.name==toBeFiled)
return floatNotice('Cannot rename '+bold(F.name));

var t='renameFolder.';
floatAsk(wtext(t+'title'),
wtext(t+'body',{FID:fid,FNAME:F.name}),
[buttonCancel(),button(wtext('next'),'renameFolderDo()')]
);
gel('newFolderName').focus();
addFolderWatcher();
}
function renameFolderDo(){
var fid=renameFolder.fid,
t='addFolder.',
fname=gel('newFolderName').value,
back='renameFolder('+fid+');';
if(fname=='')
return gel('renameFolder_msg').innerHTML=wtext(t+'noname');

if(getFolderByName(fname,getFolderById(fid).parentid))
return gel('renameFolder_msg').innerHTML=wtext(t+'duplicateName');

floatProgress();
var data='renameFolder='+fid+
'&name='+escape(fname)+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statstr,resp){
fH();
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
tree_loadData(function(){
showFolder(fid);
if(renameFolder.callback)renameFolder.callback();
});
gel('emailDIV').innerHTML='';
});
}

function postmarkNotes(pid){

var t='postmarkNotes.',
totCentCred=account.presonalCentCredits+account.groupCentCredits;
if(!isProjectParticipant(pid))
return floatNotice(wtext(t+'error.notpart'));
if(totCentCred <100){
purchaseReturn=function(){
showProject(getProjectById(pid).folderid,pid);
postmarkNotes(pid);
};
return floatAsk(wtext(t+'buy.title'),
wtext(t+'buy.body',{CREDITS:(totCentCred/100)}),
[buttonCancel(),
button(wtext('next'),'purchaseCredits()',null,'Green')]
);
}
postmarkNotesAsk(pid);
}

function postmarkNotesAsk(pid){

var t='postmarkNotes.',
html=iForm('postmarkNotesDo('+pid+')')+
wtext(t+'body',{TERMSURL:SYSINFO.termsurl})+'<br/>\n'+
'<span id=postmarkNotesAskMsg class=errorMsg></span><br/>\n'+
'<input type=radio id=tac_agree name=tac_agree value=agree /><label for=tac_agree>'+wtext(t+'agree')+'</label><br/>\n'+
'<input type=radio id=tac_notagree name=tac_agree value=notagree CHECKED /><label for=tac_notagree>'+wtext(t+'disagree')+'</label>\n'+
'</form>';
floatAsk(wtext(t+'title'),html,
[buttonCancel(),
buttonS(wtext('next'),'postmarkButton')]
);
postmarkTACWatcher(true);
}

function postmarkNotesDo(pid){

var msg=gel('postmarkNotesAskMsg'),
v=getCheckedValue(gel('tac_agree').form.tac_agree);
if(v==''){
msg.innerHTML=wtext('postmarkNotes.agreeMissing');
return false;
}
if(v=='notagree'){
fH();
return false;
}

var data='postmarkNotes='+pid+
'&wxpauth='+wxpauth;
floatProgress();
ckajax.getText(base(data),data,function(stat,statStr,resp){
fH();
if(resp.indexOf('Error:')!=-1)
return floatError(resp);

tree_loadData(function(){
updateAccountBalance();
showProject(getProjectById(pid).folderid,pid,true);
});
});
}

function addFile(pid){

var t='addFile.',
totCentCred=account.presonalCentCredits+account.groupCentCredits;
if(!isProjectParticipant(pid))
return floatNotice(wtext(t+'error.notpart'));

if(totCentCred <100){

purchaseReturn=function(){
showProject(getProjectById(pid).folderid,pid);
addFile(pid);
};
return floatAsk(wtext(t+'buy.title'),
wtext(t+'buy.body',{
CREDITS:(totCentCred/100),
TERMSURL:SYSINFO.termsurl
}),
[buttonCancel(),
button(wtext('next'),'purchaseCredits()',null,'Green')]
);
}
addFileAsk(pid);
}

var addFileID,addFile_pid;
function genAddFileID(){

addFileID=(new Date()).getTime()+'-'+
(''+Math.floor(1e7*Math.random())).substr(0,6);
return addFileID;
}
function addFileAsk(pid){

addFile_pid=0;
var W=getProjectById(pid),
F=getFolderById(W.folderid),
fname=F?F.name:'',
t='addFile.',
html='<form id=form1 enctype="multipart/form-data" action="'+APP+'?uploadFile='+pid+'&wxpauth='+wxpauth+'" target=hiddenFrame METHOD=POST '+
'onsubmit="try{if(!addFileDo('+pid+'))return false;}catch(e){floatError(e);return false;}submit();">\n'+
'<input type=hidden id="APC_UPLOAD_PROGRESS" name="APC_UPLOAD_PROGRESS" value="'+genAddFileID()+'"/>\n'+
'<span id=addFileAskMsg class=errorMsg></span><br/>\n'+
wtext(t+'body',{TERMSURL:SYSINFO.termsurl,PROJECT:W.name,FOLDER:fname})+'<br/>\n'+
'<input type=radio id=tac_agree name=tac_agree value=agree /><label for=tac_agree>'+wtext(t+'agree')+'</label><br/>\n'+
'<input type=radio id=tac_notagree name=tac_agree value=notagree CHECKED /><label for=tac_notagree>'+wtext(t+'disagree')+'</label><br/>\n'+
'<table class=tightT><tr><td id=tacHide style="display:none">'+
'<br/>\n'+
wtext(t+'do.body')+
'<input id=uploadedFile0 name=uploadedFile0 type=file />'+
'<span id=moreFiles></span>\n'+
'</td></tr></table>'+
'<iframe src=i/1.gif name=hiddenFrame id=hiddenFrame style="display:none"></iframe>'+
'</form>';
floatAsk(wtext(t+'title'),html,
[buttonCancel(),
button(wtext('next'),'gel(\'form1\').onsubmit()','postmarkButton')]
);
postmarkTACWatcher(true);
}

var postmarkTACWatcher_run=false;
function postmarkTACWatcher(r){

if(postmarkTACWatcher.run)
clearTimeout(postmarkTACWatcher.timeout);
if(r)
postmarkTACWatcher.run=r;
if(!gel('tac_agree'))
return;


var t=getCheckedValue(gel('tac_agree').form.tac_agree)=='agree';


var up=gel('uploadedFile0');
up=up?(up.value.length!=0):true;

var b='postmarkButton';
if(!gel(b))
b='signupSubmit';

if(t&&up){
enableButton(b);
}else{
disableButton(b);
}

if(gel('tacHide'))
gel('tacHide').style.display=t?'':'none';

postmarkTACWatcher.timeout=setTimeout(postmarkTACWatcher,250);
}

function addFileDo(pid){

var W=getProjectById(pid),
msg=gel('addFileAskMsg'),
v=getCheckedValue(gel('tac_agree').form.tac_agree);
if(v==''){
msg.innerHTML=wtext('addFile.agreeMissing');
return false;
}
if(v=='notagree'){
fH();
return false;
}

var filename,filepath=gel('uploadedFile0').value;

if(filepath.charAt(1)==':'){
var arr=filepath.split('\\');
filename=arr[arr.length-1];
}else{
var arr=filepath.split('/');
filename=arr[arr.length-1];
}


window.scroll(0,0);

fH();
addFile_pid=pid;
floatAsk(wtext('addFile.loadingTitle'),
wtext('addFile.loading',{PROJECTNAME:W.name}),
[],2);

setTimeout(addFileProg,1000);
return true;
}

var addFileState=[];
function addFileProg(){

var n=0;
if(addFileState.timeout)
clearTimeout (addFileState.timeout);

addFileState={
START:n++,
UPLOAD:n++,
UPLOADSIZE:n++,
CREDITS:n++,
ARCH1:n++,
ARCH2:n++,
HASH:n++,
LOG:n++,
SIGN:n++,
EPMREQ:n++,
EPMRESP:n++,
EPMARCH1:n++,
EPMARCH2:n++,
EPMEMAIL:n++,
EPMLOG:n++,
NOW:0,
CANCEL:0
};
addFileState.uploadComplete=0;
addFileProg_();
}
function addFileTooBig(){

fC();
var t='addFile.toobig.'
return floatAsk(wtext(t+'title'),
wtext(t+'body',{MAX:humanSize(MAX.upload.bytes)}),
[button(wtext(t+'okButton'),'fH()')]
);
}
function addFileAgain(msg){

var id=gel('APC_UPLOAD_PROGRESS');
if(!id)
return;

gel('hiddenFrame').src='i/1.gif';
fH();
fC(2);
blanketScreen();
floatShow(1);

if(addFileState.timeout)
clearTimeout(addFileState.timeout);

id.value=genAddFileID();
gel('addFileAskMsg').innerHTML=msg;
}

function addFileTimeout(n){

if(addFileState.NOW>addFileState.UPLOAD)
return;

if(addFileState.bytes <=n)
return addFileAgain(wtext('addFile.error.interrupt'));
}

function addFileProg_(){

if(addFileState.CANCEL)
return;

var imgs={
PEND:'check_no.gif',
LOAD:'loading.gif',
DONE:'check_yes.gif'
};
var I=function(done,load){
try{
if(done)
gel(done+'Img').innerHTML='<img src="i/'+imgs.DONE+'">';
if(load)
gel(load+'Img').innerHTML='<img src="i/'+imgs.LOAD+'">';
}catch(e){}
}
var msg=gel('upProgTxt');

var data='getUploadStatus='+addFileID
+'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(addFileState.CANCEL)
return;
if(resp.indexOf('Error: ')!=-1){
addFileState.CANCEL=1;
if(addFileState.NOW>addFileState.UPLOAD){
if(resp.toLowerCase().indexOf('communication error')!=-1){
return floatAsk(wtext('addFile.error.comError.title'),
wtext('addFile.error.comError'),
[button(wtext('close'),'fH()')],
3);
}else{
return floatError(resp.substr(7));
}
}else if(addFileState.NOW==addFileState.START){
return addFileAgain(wtext('addFile.error.interrupt'));}
}

if(!msg)
return;

var R=parseResponse(resp);
if(R.error){
R.error=''+R.error;
if(R.error.indexOf('Uploaded file exceeds maxium size')!=-1)
return addFileTooBig();
if(R.error.indexOf('Upload was interrupted.')!=-1)
return addFileAgain(wtext('addFile.error.interrupt'));

gel('upProgImg').innerHTML=bold('Interrupted.');
gel('upCancel').style.display='none';
gel('upClose').style.display='none';
gel('upCompleteClose').style.display='';
return msg.innerHTML='<span class=red>'+R.error+'</span>';
}

var U=R.upload;
if(U)U=U[0];
var P=R.processing;
if(P)P=P[0];

var timeout=1000,
t='upStep';

if(U&&U.current!=0){
var rate=U.current / (U.now-U.start),
prog=dec2(U.current / U.total * 10000),
eta=humanTime((U.total-U.current)/ rate);
rate=dec2(rate/10.24);
addFileState.bytes=U.current;
if(addFileState.timeout)
clearTimeout(addFileState.timeout);
addFileState.timeout=setTimeout('addFileTimeout('+U.current+')',MAX.upload.timeout);
}

if(U&&U.current!=0)
switch (addFileState.NOW){
case addFileState.START:
msg.innerHTML=bold('['+humanSize(U.current)+' '+prog+'%&nbsp;'+rate+'KB/sec ETA:'+eta+']');
I(null,t+'Name');

addFileState.NOW++;
break;

case addFileState.UPLOAD:
msg.innerHTML=bold('['+humanSize(U.current)+' '+prog+'%&nbsp;'+rate+'KB/sec ETA:'+eta+']');
addFileState.uploadComplete=U.now*1;
I(t+'Name',t+'Size');
if(gel(t+'Name'))gel(t+'Name').innerHTML=b64dec(U.name);

if(U.total>MAX.upload.bytes)
return addFileTooBig();

if(U.done==1){
gel('upCancel').style.display='none';
gel('upClose').style.display='';
addFileState.NOW++;
}
break;

case addFileState.UPLOADSIZE:
msg.innerHTML=bold('Upload Complete');
I(t+'Size',t+'Credits');
gel(t+'Size').innerHTML=humanSize(U.total,true);
addFileState.NOW++;
break;

case addFileState.CREDITS:
I(t+'Credits',t+'Arch1');
gel(t+'Credits').style.display='';
addFileState.NOW++;
break;

case addFileState.ARCH1:
I(t+'Arch1',t+'Arch2');
gel(t+'Arch1').style.display='';
addFileState.NOW++;
break;

case addFileState.ARCH2:
I(t+'Arch2',t+'Hash');
gel(t+'Arch2').style.display='';
addFileState.NOW++;
break;

case addFileState.HASH:
I(t+'Hash',t+'Log');
gel(t+'Hash').innerHTML=fixWidth(b64hex(P.hash));
addFileState.NOW++;
break;

case addFileState.LOG:
I(t+'Log',t+'Sign');
gel(t+'Log').style.display='';
addFileState.NOW++;


showProject_newest=true;
pid=addFile_pid;
showProject(getProjectById(pid).folderid,pid,true);

break;

case addFileState.SIGN:
I(t+'Sign',t+'EPMReq');
gel(t+'Sign').style.display='';
addFileState.NOW++;
break;

case addFileState.EPMREQ:
I(t+'EPMReq',t+'EPMResp');
gel(t+'EPMReq').style.display='';

if(P.epmtrankey!='')
addFileState.NOW++;


break;

case addFileState.EPMRESP:
I(t+'EPMResp',t+'EPMArch1');
gel(t+'EPMResp').innerHTML=
'<acronym title="Tracking number issued by the USPS">USPS Tracking</acronym>: '+P.epmtrankey+'<br/>'+
'<acronym title="Date and time when the post office witnessed this transaction">Postmark Date</acronym>: '+local(P.postmarkdate);

addFileState.NOW++;
break;

case addFileState.EPMARCH1:
I(t+'EPMArch1',t+'EPMArch2');
gel(t+'EPMArch1').style.display='';
addFileState.NOW++;
break;

case addFileState.EPMARCH2:
I(t+'EPMArch2',t+'EPMEmail');
gel(t+'EPMArch2').style.display='';
addFileState.NOW++;
break;

case addFileState.EPMEMAIL:
I(t+'EPMEmail',t+'EPMLog');
gel(t+'EPMEmail').style.display='';
addFileState.NOW++;
break;

case addFileState.EPMLOG:
I(t+'EPMLog');
gel(t+'EPMLog').style.display='';


showProject_newest=true;
pid=addFile_pid;
showProject(getProjectById(pid).folderid,pid,true);

gel('upProgImg').innerHTML=bold('Completed!');

gel('upClose').style.display='none';
gel('upCompleteClose').style.display='';
return;

default:
debug('impossible state');
return;
}


if(addFileState.UPLOAD <addFileState.NOW){
var u=addFileState.uploadComplete,
s=(new Date(u*1000)).getSeconds(),
epmActionAt=u+((s-15+60)%60);
timeout=(epmActionAt-u)/ (addFileState.EPMRESP-addFileState.UPLOAD)* 1000;
if(timeout <1000)
timeout=1000;

if(addFileState.NOW==addFileState.CREDITS)
timeout=500;
}


setTimeout(addFileProg_,timeout);
});
}
function addFileCancel(){

addFileState.CANCEL=1;
if(addFileState.timeout)
clearTimeout(addFileState.timeout);
setTimeout(floatClean,250);
}

function addFileDone(id){

var pid=addFile_pid;

if(id.indexOf('Error: File is too large or completely empty.')!=-1){
floatShow(1);
blanketScreen();
gel('addFileAskMsg').innerHTML=wtext('addFile.done.nofile');
return;
}
else if(id.indexOf('Error: File is a windows CDA')!=-1){
fC();
return floatError(wtext('addFile.error.invalidFile.cda'));
}
else if(id.indexOf('Error:')!=-1){
fC();
return floatError(id);
}

updateAccountBalance();
}

var fileAction_=[];
function fileAction(act){
if(act=='')
return;

var t='fileAction.',sel=[];
for(var i=0;i<10000;i++){
var c=gel('notec'+i);
if(c&&c.checked)
sel[sel.length]=notes[i].fileid;
}

if(act=='move'){
if(sel.length==0)
return floatError(wtext(t+'nonesel'))
var V=getwxpview().split('x');
moveFiles(V[1]*1,sel);
}
}

var moveA=[],
moveFiles_=[];
function moveFiles(project,files){

fH();
if(!project&&!files){
files=moveFiles_.files
project=moveFiles_.project
}
moveFiles_.project=project;
moveFiles_.files=files;
var t='moveFiles.',
W=getProjectById(project),
sub='your files',full='Your files:<br/>';
if(files.length==1)
sub=full=getFileById(files[0]).name;
else for(var i=0;i<files.length;i++)
full+='&nbsp;-&nbsp;'+getFileById(files[i]).name+'<br/>';

floatAsk(wtext(t+'title'),
wtext(t+'body',{
WIDTH:'200px',
HEIGHT:'300px',
FILES:floatText(sub,full,1),
FOLDERPROJECTTREE:tree_(topFolder,'moveFilesFSel','moveFilesWSel',true)
}),
[buttonCancel(),
button(wtext(t+'makeFolderButton'),'addFolder(getVal(\'moveFID\'),function(){moveFiles()})','moveAddFolder'),
button(wtext(t+'makeProjectButton'),'addProject(getVal(\'moveFID\'),function(){moveFiles()})','moveAddProject'),
button(wtext('next'),'moveFilesDo()','moveMoveFile')]
);

var div=gel('folderTree'),link=gel('getSubList_last');
if(link)
div.scrollTop=getObjectOffset(link).y-getObjectOffset(div).y;

moveA={
go:'moveMoveFile',
addF:'moveAddFolder',
addW:'moveAddProject',
FID:gel('moveFID'),
PID:gel('movePID'),
dest:gel('moveDestination')
};
disableButton(moveA.go);
disableButton(moveA.addF);
disableButton(moveA.addW);
}
function moveFilesFSel(tfid){

var t='moveFiles.error.',
tF=getFolderById(tfid);

disableButton(moveA.go);
enableButton(moveA.addF);
enableButton(moveA.addW);

moveA.dest.innerHTML=wtext(t+'folder');
moveA.FID.value=tfid;
moveA.PID.value=-1;
}
function moveFilesWSel(tfid,tpid){
debug('moveFilesWSel('+tfid+','+tpid+')');
var t='moveFiles.error.',
tP=getProjectById(tpid),
W=getProjectById(moveFiles_.project);

enableButton(moveA.go);
disableButton(moveA.addF);
disableButton(moveA.addW);

if(W.id==tP.id){
moveA.dest.innerHTML=wtext(t+'sameProject');
moveA.PID.value=-1;
moveA.FID.value=-1;
return;
}
if(tP.id <0){
moveA.dest.innerHTML=wtext(t+'notHere',{FNAME:recipProject.name});
return;
}

moveA.dest.innerHTML=bold(tP.name);
moveA.PID.value=tP.id;
moveA.FID.value=-1;
}
function moveFilesDo(){

var str='',
tpid=getVal('movePID');

if(tpid==-1)
return gel('moveDestination').innerHTML=wtext('moveFiles.error.noProject');

for(var i=0;i<moveFiles_.files.length;i++)
str+=moveFiles_.files[i]+',';
str=str.substr(0,str.length-1);

floatProgress();

var data='moveFiles='+str
+'&projectid='+tpid
+'&wxpauth='+wxpauth,
o=gel('checkall');

o.checked=false;
checkAllNotes(o);

ckajax.getText(base(data),data,function(stat,statstr,resp){
fH();
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
tree_loadData(function(){

showProject(getProjectById(tpid).folderid,tpid,false);
});
});
}

var moveUser_groups=[],
moveUser_uid,
moveUser_gid;
function moveUserGroup(gid,uid){

moveUser_gid=gid;
moveUser_uid=uid;
var t='moveUserGroup.',
U=getUserById(uid),
html=iForm('moveUserGroupDo()')+
iHide('moveGID',-1)+
wtext(t+'body',{USERNAME:U.name,GROUPTREE:getGroupList(moveUser_groups,gid,'moveUserGroupGSel')})+
'</form>';
floatAsk(wtext(t+'title'),html,
[buttonCancel(),
button(wtext(t+'newGroupButton'),'firmAddGroup(\'moveUserGroup('+gid+','+uid+')\')'),
buttonS(wtext('next'),'moveButton')]
);
disableButton('moveButton');
}
function getGroupById(G,id){
if(id!=0&&G)
for(var i=0;i<G.length;i++)
if(G[i].id==id)
return G[i];
return{id:-1,name:'<span style="font-style:italic;color:#cccccc">none id#'+id+'</span>',type:'user'};
}
function moveUserGroupGSel(tgid){

var gname=gel('moveDestination'),
moveGID=gel('moveGID'),
moveB='moveButton',
tG=getGroupById(moveUser_groups,tgid);

if(moveUser_gid==tgid){
gname.innerHTML=wtext('moveUserGroup.error.sameGroup');
moveGID.value=-1;
disableButton(moveB);
return;
}

gname.innerHTML=tG.name;
moveGID.value=tG.id;
enableButton(moveB);
}
function moveUserGroupDo(){

var data='moveUserGroup='+moveUser_uid
+'&oldgroup='+moveUser_gid
+'&newgroup='+getVal('moveGID')
+'&wxpauth='+wxpauth;

floatProgress();
ckajax.getText(base(data),data,function(stat,statstr,resp){
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
fH();
showFirmAdmin();
});
}

function firmRenameGroup(gid){
var t='firmRenameGroup.';
floatAsk(wtext(t+'title'),
wtext(t+'body',{GROUPID:gid,GROUPNAME:getGroupById(moveUser_groups,gid).name}),
[buttonCancel(),
button(wtext('next'),'firmRenameGroup()')]
);
}
function firmRenameGroupDo(){
var newname=getVal('newgroupname'),
gid=getVal('groupid'),
data='firmRenameGroup='+gid
+'&newname='+newname
+'&wxpauth'+wxpauth;

floatProgress();
ckajax.getText(base(data),data,function(stat,statstr,resp){
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
fH();
showFirmAdmin();
});
}

var firmAddGroup_fcn=null;
function firmAddGroup(fcn){

firmAddGroup_fcn=fcn;
var t='firmAddGroup.';
floatAsk(wtext(t+'title'),
wtext(t+'body',{GNAME:''}),
[buttonCancel(),
button(wtext('next'),'firmAddGroupDo()')]
);
gel('addGroupName').focus();
}
function firmAddGroupDo(){

var gname=getVal('addGroupName'),
data='firmAddGroup='+escape(gname)
+'&wxpauth='+wxpauth;

floatProgress();
ckajax.getText(base(data),data,function(stat,statstr,resp){
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
fH();
if(firmAddGroup_fcn)
firmAddGroup_fcn();
});
}

function moveProject(pid){


if(pid==recipProject.id)
return floatNotice('Cannot move '+bold(recipProject.name));
if(pid <0)
return floatNotice('Cannot move '+bold(getProjectById(pid).name));

moveProject.pid=pid;
moveProject.target=-1;
var t='moveProject.';
floatAsk(wtext(t+'title'),
wtext(t+'body',{
WIDTH:'200px',
HEIGHT:'300px',
PID:pid,
NAME:getProjectById(pid).name,
FOLDERTREE:tree_(topFolder,'moveProjectFSel',null,true)
}),
[buttonCancel(),button(wtext('next'),'moveProjectDo()')]
);
}
function moveProjectFSel(tfid){

var fname=gel('moveDestination'),
W=getProjectById(moveProject.pid),
tF=getFolderById(tfid);

if(tfid==0){
fname.innerHTML=wtext('moveProject.error.myFolders');
moveProject.target=-1;
return;
}
if(W.folderid==tfid){
fname.innerHTML=wtext('moveProject.error.sameFolder');
moveProject.target=-1;
return;
}

fname.innerHTML=tF.name;
moveProject.target=tF.id;
}

var addProjectCB=null;
function addProject(fid,fcn){
var V=getwxpview().split('x');

if(!fid){
fid=V[0]*1;

}

var t='addProject.',
wname=getVal('addProjectName');
if(!wname)
wname='';
addProjectCB=fcn;
floatAsk(wtext(t+'title'),
wtext(t+'body',{FID:fid,FOLDER:getTreeViewSimple(fid,0),WNAME:wname}),
[buttonCancel(),
button(wtext('next'),'addProjectDo('+fid+')')]
);
addProjectWatcher();
setTimeout("gel('addProjectName').focus()",250);
}

function addProjectWatcher(){

var vals=alphabet+nums+'_-'+' ',
a=gel('addProjectName'),
b=gel('moveProjectName');
if(!a&&!b)return;
checkField(a,vals,32);
checkField(b,vals,32);

setTimeout(addProjectWatcher,250);
}

function addProjectDo(fid){

var wname=gel('addProjectName').value,
back='addProject('+fid+')';
if(wname=='')
return floatNotice(wtext('addProject.noname'),back);



if(getProjectByName(wname,fid))
return floatNotice(wtext('addProject.duplicateName'),back);

floatProgress();

var data='addProject='+escape(wname)+
'&folderid='+fid+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statstr,resp){
fH();
if(resp.indexOf('OK: ')!=0)
return floatError(resp);
tree_loadData(function(){
var newpid=resp.split(' ')[1];

showProject(fid,newpid);
if(addProjectCB)
addProjectCB();
});
});
}

function moveProjectDo(){

var pid=moveProject.pid,
tfid=moveProject.target;

if(tfid==-1)
return gel('moveDestination').innerHTML=wtext('moveProject.error.noFolder');

floatProgress();

var t='moveProject.exist.',
data='moveProject='+pid+
'&folderid='+tfid+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statstr,resp){
fH();
if(resp.indexOf('OK')!=0)
if(resp.indexOf('already exists')!=-1)
return floatAsk(wtext(t+'title'),wtext(t+'body'),
[button(wtext('cancel'),'fH()'),
button(wtext(t+'rename'),'renameProject('+pid+',moveProjectDo)')]
);
else
return floatError(resp);
tree_loadData(function(){

showProject(tfid,pid);
});
});
}

function renameItem(){

var V=getwxpview().split('x');
if(V[1]!=0)
return renameProject(V[1]);
return renameFolder(V[0]);
}

function delItem(){

var V=getwxpview().split('x');
if(V[1]!=0)
return delProject(V[1]);
return delFolder(V[0]);
}

function moveItem(){

var V=getwxpview().split('x');
if(V[1]!=0)
return moveProject(V[1]);
return moveFolder(V[0]);
}

function moveFolder(fid){

if(fid==topFolder.id)
return floatNotice('Cannot move '+bold(topFolder.name));
if(fid==sharedFolder.id)
return floatNotice('Cannot move '+bold(sharedFolder.name));

moveFolder.fid=fid;
moveFolder.target=-1;
var t='moveFolder.',
F=getFolderById(fid);
if(F&&F.name==toBeFiled)
return floatError('Cannot move '+bold(F.name));

floatAsk(wtext(t+'title'),
wtext(t+'body',{
WIDTH:'200px',
HEIGHT:'300px',
FID:fid,
NAME:F.name,
FOLDERTREE:tree_(topFolder,'moveFolderFSel',null,true)
}),
[buttonCancel(),button(wtext('next'),'moveFolderDo()')]
);
addFolderWatcher();
}
function setIFrameHtml(id,html){

var I=gel(id);
I=(I.contentWindow?I.contentWindow:(I.contentDocument.document?I.contentDocument.document:I.contentDocument));
var d=I.document;
d.open();
d.write(html);
d.close();
}
function moveFolderFSel(tfid){

var fname=gel('moveDestination'),
F=getFolderById(moveFolder.fid),
tF=getFolderById(tfid);

if(F.id==tfid||isSubFolderOf(F.id,tfid)){
fname.innerHTML=wtext('moveFolder.error.selfFolder');
moveFolder.target=-2;
return;
}
if(F.parentid==tfid){
fname.innerHTML=wtext('moveFolder.error.sameFolder');
moveFolder.target=-2;
return;
}

if(!tF)
tF=topFolder;
fname.innerHTML=tF.name;
moveFolder.target=tF.id;
}

var addFolderCB=null;
function addFolder(fid,fcn){
var V=getwxpview().split('x');
if(!fid){
fid=V[0]*1;

}

debug('addFolder('+fid+','+fcn+')');
var t='addFolder.',
fname=getVal('newFolderName');
if(!fname)
fname='';
if(getFolderById(fid)==null&&fid!=0)
return floatError('No folder selected');
addFolderCB=fcn;
floatAsk(wtext('addFolder.title'),
wtext(t+'body',{FID:fid,FOLDER:getTreeViewSimple(fid,0),FNAME:fname}),
[buttonCancel(),button(wtext('next'),'addFolderDo('+fid+')')]
);
gel('newFolderName').focus();
addFolderWatcher();
}

function addFolderWatcher(){

var vals=alphabet+nums+'_-'+' ',
a=gel('moveFolderName'),
b=gel('newFolderName');
if(!a&&!b)return;
checkField(a,vals,32);
checkField(b,vals,32);

setTimeout(addFolderWatcher,250);
}

function addFolderDo(fid){

var fname=getVal('newFolderName'),
back='addFolder('+fid+')';
if(!fname||fname=='')
return floatNotice(wtext('addFolder.noname'),back);

if(getFolderByName(fname,fid))
return floatNotice(wtext('addFolder.duplicateName'),back);

floatProgress();

var data='addFolder='+escape(fname)+
'&parentid='+fid+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statstr,resp){
fH();
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
tree_loadData(function(){
var R=parseResponse(resp);

showFolder(R.newfid);
if(addFolderCB)
addFolderCB();
});
});
}

function moveFolderDo(){

var fid=moveFolder.fid,
tfid=moveFolder.target;

if(tfid==-2)
return;
if(tfid==-1)
return gel('moveDestination').innerHTML=wtext('moveFolder.error.noFolder');

floatProgress();

var t='moveFolder.exist.',
data='moveFolder='+fid+
'&parentid='+tfid+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statstr,resp){
fH();
if(resp.indexOf('Error:')!=-1){
if(resp.indexOf('already exists')!=-1){
return floatAsk(wtext(t+'title'),wtext(t+'body'),
[button(wtext('cancel'),'fH()'),
button(wtext(t+'rename'),'renameFolder('+fid+',moveFolderDo)')]
);
}else{
return floatError(resp);
}
}
tree_loadData(function(){

showFolder(fid);
});
});
}




function getFolderById(id){

for(var i=0;i<folders.length;i++)
if(folders[i].id==id)
return folders[i];
return null;
}

function getFolderByName(n,pfid){

for(var i=0;i<folders.length;i++)
if(folders[i].parentid==pfid&&folders[i].name==n)
return folders[i];
return null;
}

function getSubFoldersById(id,filter){

var ret=[];
for(var i=0;i<folders.length;i++)
if(folders[i].parentid==id)
if(!filter||folders[i].name==filter)
ret[ret.length]=folders[i];
return ret;
}

function getRecipProjectByUserId(id){
var P;
if(!(P=getRecipProjectByUserId.proj)){
P=getRecipProjectByUserId.proj={};
P.length=0;
}
if(!P['id'+id])
P['id'+id]={id:(-100-P.length++),name:getUserById(id).email,folderid:0};
return P['id'+id].id;
}
function getProjectById(id){

if(P=getRecipProjectByUserId.proj)
for(var i in P)
if(P[i].id==id)
return P[i];
for(var i=0;i<projects.length;i++)
if(projects[i].id==id)
return projects[i];
return null;
}

function getProjectByName(n,fid){

var u=getUserId(),P=projects;
for(var i=0;i<P.length;i++){
if(P[i].folderid==fid&&P[i].ownerid==u&&P[i].name==n)
return P[i];
}
return null;
}

function isProjectParticipant(pid){

var P=getProjectById(pid).participants;
var u=getUserId();
for(var i=0;i<P.length;i++)
if(P[i]==u)
return true;
return false;
}

function getSubProjectsById(id,filter){

var ret=[];
for(var i=0;i<projects.length;i++)
if(projects[i].folderid==id)
if(!filter||projects[i].name==filter)
ret[ret.length]=projects[i];
return ret;
}

function countSubItems(fid){
debug('countSubItems('+fid+')');
if(fid==sharedFolder.id){
var fs=','; 
for(var i=0;i<folders.length;i++)
fs+=folders[i].id+',';
var r=0;
for(var i=0;i<projects.length;i++)
r+=fs.indexOf(','+projects[i].folderid+',')==-1;
return r;
}

return getSubFoldersById(fid).length+getSubProjectsById(fid).length;
}

function isSubFolderOf(pfid,cfid){

var cF=getFolderById(cfid);
if(!cF)
cF=topFolder;

if(cF.parentid==pfid)
return true;
if(cF.parentid <=0)
return false;

if(cF.id==cF.parentid)
return false;

return isSubFolderOf(pfid,cF.parentid);
}

function getSubList_sel(el){

var l=getSubList.last;
if(l!=null)
l.style.backgroundColor='';
else if((l=gel('getSubList_last'))!=null)
l.style.backgroundColor='';

el.style.backgroundColor='#cccccc';
getSubList.last=el;
}
function getSubFolderList(F,Ffcn,Wfcn){
alert('redo getSubFolderList()');
if(!F)
F=topFolder;

var V=getwxpview().split('x'),
ret='<table class=treeT>'+
'<tr><td align=left>'+qimg('Folder')+'</td>'+
'<td align=left>';
if(Ffcn){
var style=(V[0]!=F.id||V[1]!=0)?'':'id="getSubList_last" style="background-color:#cccccc"';
ret+='<a href="#" '+style+' onclick="getSubList_sel(this);'+Ffcn+'('+F.id+');return false">'+F.name+'</a>';
}else{
ret+=F.name;
}
ret+='<br/>';

if(Wfcn){
for(var i=0;i<projects.length;i++){
if(projects[i].folderid==F.id){
var style=(V[1]!=projects[i].id)?'':'id="getSubList_last" style="background-color:#cccccc"';
ret+='<tr><td></td>'+
'<td align=left><a href="#" '+style+' onclick="getSubList_sel(this);'+Wfcn+'('+projects[i].id+');return false">-&nbsp;'+projects[i].name+'</a><br/>';
}
}
}


for(var i=0;i<folders.length;i++)
if(folders[i].parentid==F.id)
ret+=getSubFolderList(folders[i],Ffcn,Wfcn);

return ret+'</td></tr></table>';
}
function getGroupList(G,G0,GFcn){

var ret='<table class=treeT>'+
'<tr><td align=left>+</td>'+
'<td align=left>';
ret+='Groups';
ret+='<br/>';

for(var i=0;i<G.length;i++){
var style=(G0!=G[i].id)?'':'id="getSubList_last" style="background-color:#cccccc"';
alert(G0+' '+G[i].id+'||'+style);
ret+='<tr><td></td>'+
'<td align=left><a href="#" '+style+' onclick="getSubList_sel(this);'+GFcn+'('+G[i].id+');return false">&nbsp;'+G[i].name+'</a><br/>';
}

return ret+'</td></tr></table>';
}

function getSubProjectList(F){

var ret='<table class=treeT>'+
'<tr><td>'+qimg('Folder')+'</td><td>'+F.name+'<br/>';


var w=getSubProjectsById(F.id);
for(var j=0;j<w.length;j++)
ret+='<span style="color:#003e79">-&nbsp;'+w[j].name+'</span><br/>';


for(var i=0;i<folders.length;i++)
if(folders[i].parentid==F.id)
ret+=getSubProjectList(folders[i]);

return ret+'</td></tr></table>';
}

function countFiles(pid){

var r=0;
for(var i=0;i<files.length;i++){
if(pid==-1&&getProjectById(files[i].projectid)==null)
r++;
else if(files[i].projectid==pid)
r++;
}
return r;
}

function getFileById(id){

var r;
if(r=files['id'+id])return r;

for(var i=0;i<files.length;i++)
if(files[i].id==id)
return files['id'+id]=files[i];
return null;
}
function getFileNameById(id){

var f=getFileById(id);
if(f==null)
return '';
return f.name;
}
function getEpmByFileId(id){

var r;
if(!epms)epms=[];
if(r=epms['id'+id])return r;

if(epms)
for(var i=0;i<epms.length;i++)
if(epms[i].fileid==id)
return epms['id'+id]=epms[i];
return{epmcheckdate:0,filehash:'',epmdate:0,epmtrankey:''};
}



function getInitials(u){

if(!u)return alert('getInitials u==null\n'+stackTrace());
var init='',
a='';

if(u.name!=null){
if(u.id==0)
return 'T!';
a=u.name.split(' ');
}
else if(u.disp){
a=u.disp.split(' ');
}
else{
a=u.split(' ');
}

for(var i=0;i<a.length;i++)
for(var j=0,a2=a[i].split('-');j<a2.length;j++)
for(var k=0,a3=a2[j].split('\'');k<a3.length;k++)
for(var l=0,a4=a3[k].split('@');l<a4.length;l++)
init+=a4[l].charAt(0);

return init.toUpperCase();
}

function delUserFromProject(uid,pid){

var W=getProjectById(pid),
p=W.participants,
newP=[];
for(var i=0;i<p.length;i++){
if(p[i]!=uid)
newP[newP.length]=p[i];
}
W.participants=newP;
}

function addFileToMemory(f){

f.name=b64dec(f.name);
for(var i=0;i<files.length;i++)
if(files[i].id==f.id)
return files[i]=f;
files[files.length]=f;

}

function addUserToProject(u,pid){

addUser(u);
var W=getProjectById(pid),
p=W.participants;
for(var i=0;i<p.length;i++)
if(p[i]==u.id)
return;
p[p.length]=u.id;
}

function addUserToFolder(u,fid){

addUser(u);
var F=getFolderById(fid),
p=F.participants;
if(p.length==0)
F.participants=p=[];
for(var i=0;i<p.length;i++)
if(p[i]==u.id)
return;
p[p.length]=u.id;
}

function delUserFromFolder(uid,fid){

var F=getFolderById(fid),
p=F.participants,
newP=[];
for(var i=0;i<p.length;i++){
if(p[i]!=uid)
newP[newP.length]=p[i];
}
F.participants=newP;
}

function addUser(u){

if(getUserById(u.id))
return;
u.name=b64dec(u.name);
users[users.length]=users['id'+u.id]=u;
users.size++;
}

function getUserByEmail(e){

for(var i=0;i<users.length;i++)
if(users[i].email==e)
return users[i];
return{id:-999,name:'',email:e};
}
function getUserById(id){

if(id==0)
return{id:0,email:'do_not_reply@trustifi.com',name:'TRUSTIFI'};

var r;
if(r=users['id'+id])return r;

if(users.size==null){
users.size=users.length;
for(var i=0;i<users.length;i++)
users['id'+users[i].id]=users[i];
}

return users['id'+id];
}

function getCreditById(id){
var C=epmCredits;
if(C.size==null){
epmCredits.size=C.length;
for(var i=0;i<C.length;i++)
epmCredits['id'+C[i].id]=C[i];
}

return epmCredits['id'+id];
}





function showParticipant(u,clk){

fLink++;
if(u.id==-999)
return u.email;
if(clk==null)clk='';
if(clk!='')cls=' onclick="'+clk+'"';
return '<span class=floatUser id=fLink'+fLink+' '+
'onmouseover="floatNearShow('+fLink+',showUser(getUserById('+u.id+')))" '+
clk+'>'+u.email+'</span>';
}

var fLink=0,
fText=[],
fTextCache=[],
fMenus=[];
function floatMenu(t,L){

fLink++;
fMenus['n'+fLink]=L;
return '[<a id=fLink'+fLink+' href="#" onclick="try{floatNearMenu('+fLink+')}catch(e){floatError(e)}return false" style="font-weight:bold">'+t+'</a>]';
}


function floatText(txt,full,under){
var n=++fLink;
under=under?'style="text-decoration:underline"':'';
return parseTmpl('<span class=floating id="fLink{N}" '+
'{UNDER}'+'onmouseover="floatNearShow({N},unescape(\'{FULL}\'))">{TXT}</span>',
{N:n,TXT:txt,FULL:escape(full),UNDER:under});
}
function truncText(t,l){
return t.length <=l?t:t.substring(0,l-3)+'...';
}


function floatTruncText(t,l,s){
if(!l){
return t;
}
if(t.length <l)
return t;

var n=++fLink;
if(!s)s='font-family:monospace'
return parseTmpl('<span class=floating style="'+s+'" onmouseover="floatNearShow({N},unescape(\'{FULL}\'))" id=fLink{N}>{SUB}</span>',
{N:n,FULL:escape(nobr(t)),SUB:truncText(t,l)});
}


function floatTrimText(t,px,fl){
if(!px){
debug('floatTrimText px='+px+'  t='+t);
return t;
}
var n=++fLink;
fText[fText.length]={id:'fLink'+fLink,t:t,px:px,l:t.length};
fl=fl?'onmouseover="floatNearShow({N},unescape(\'{FULL}\'))"':'';
return parseTmpl('<span class=floating style="font-family:monospace;" '+fl+' id=fLink{N}>{TXT}</span>',
{N:n,FULL:escape(t),TXT:t});
}
function floatTrimTextUpdate(){

var n=0,arr=[],cache=[],
TRIM=function(e,T){
e.innerHTML=T.t.substring(0,T.l)+(T.l!=T.t.length?'...':'');
};

for(var i=0;i<fText.length;i++){
var T=fText[i],
e=gel(T.id);
if(!e)continue;
arr[arr.length]=T;
if(e.offsetWidth==0)continue;



if(fTextCache[T.t+'_'+T.px]){
T.l=fTextCache[T.t+'_'+T.px];
TRIM(e,T);

}

if(T.l!=T.t.length&&e.offsetWidth <T.px -12){

T.l+=1;
TRIM(e,T);
n++;

}
else if(e.offsetWidth>T.px){
var x=Math.floor((e.offsetWidth-T.px)/6);
x=x>0?x:1;

T.l-=x;
TRIM(e,T);
n++;

}
else{
fTextCache[T.t+'_'+T.px]=T.l;

}
}

fText=arr;


if(n!=0)debug('floatTrimTextUpdate()end n='+n+' tot='+fText.length);
setTimeout(floatTrimTextUpdate,n==0?1000:500);
}

function floatUser(id,px){

var n=++fLink;
return parseTmpl('<span class=floating id=fLink{N}'+
' onmouseover="floatNearShow({N},showUser(getUserById({ID})))">{TXT}</span>',
{N:n,ID:id,TXT:getInitials(getUserById(id))});
}
function floatEmail(e,l){
debug('floatEmail('+e.addr+'|'+e.disp+','+l+')');
fLink++;

e.disp=strReplace(strReplace(strReplace(
e.disp,
'"','&quot;'),		
'\'','::TICK::'),	
'::TICK::','\\\'');	
var str=e.addr.length <l?e.addr:e.addr.substring(0,l-3)+'...';

debug('str='+e.disp+'==>'+str);
return '<span class=floating style="font-family:Courier new,monospace" id=fLink'+fLink+' '+
'onmouseover="floatNearShow('+fLink+',\''+nobr(e.disp+' &amp;lt;'+e.addr+'&amp;gt;')+'\')">'+
str+'</span>';
}

function showUser(u){

if(!u)return alert('showUser u==null\n'+stackTrace());
return nobr(u.name+' &lt;'+u.email+'&gt;');
}





function floatTime(t,c){

fLink++;
c=(c&&t <gmtime())?'alert':'floating';
return '<span class="'+c+'" id=fLink'+fLink+
' onmouseover="floatNearShow('+fLink+',gmt2local('+t+'))">'+
gmt2localshort(t)+'</span>';
}
function floatExpiryTime(t,c){

fLink++;
c=(c&&t <gmtime())?'alert':'floating';
return '<span class="'+c+'" id=fLink'+fLink+
' onmouseover="floatNearShow('+fLink+',gmt2local('+t+'))">'+
(t<gmtime()?'Expired':gmt2localshort(t))+'</span>';
}





function floatTimeFull(t,c,l2){

fLink++;
c=(c&&t <gmtime())?'alert':'floating';
return '<span class="'+c+'" id=fLink'+fLink+
' onmouseover="floatNearShow('+fLink+',gmt2local('+t+'))">'+
(l2?gmt2local2line(t):gmt2local(t))+'</span>';
}




function floatGmtFull(t,c){

fLink++;
c=(c&&t <gmtime())?'alert':'floating';
return '<span class="'+c+'" id=fLink'+fLink+
' onmouseover="floatNearShow('+fLink+',gmt2local('+t+'))">'+
gmt(t)+'</span>';
}

function floatNearMenu(n){

var fl=gel('fLink'+n),
e=gel('floater2'),
s=e.style,
L=fMenus['n'+n],
html='<table class=pad2>';
for(var i=0;i<L.length;i++)
html+=trtdlnw('-&nbsp;'+L[i]);
html+='<tr><td style="white-space:nowrap;background:#015994;color:#ffffff">['+iLink('gel(\'floater2\').style.display=\'none\'','Hide',null,'color:#ffffff')+']</td></tr>'+
'</table>';

if(!fl)
fl=n;

e.innerHTML=html;

s.display='';
s.backgroundColor='#ffffff';
s.position='absolute';
s.padding='2px';
s.font='12px normal sans-serif';
s.border='1px solid #015994';
floatNearPosition(e,fl,html.indexOf('<br/>')!=-1);
}

function floatNearShow(n,html,under){
if(!floatNearShow.to)
floatNearShow.to=[];

var fl=gel('fLink'+n),
e=gel('floater2'),
s=e.style;

if(!fl)
if(!(fl=gel(n)))
fl=n;

fl.onmouseout=function(){
var f=gel('floater2');
if(!f.to)return;
clearTimeout(f.to);
f.to=0;
f.style.display='none';
};
e.to=setTimeout(function(){fl.onmouseout()},2000);
e.innerHTML=html;

s.display='';
s.backgroundColor='#ffffff';
s.position='absolute';
s.padding='2px';
s.font='12px normal sans-serif';
s.border='1px solid #015994';
s.textAlign='left';
floatNearPosition(e,fl,html.indexOf('<br/>')!=-1,under);
}
function floatNearPosition(d,s,extra,under){

if(s.offsetParent){
var O=getObjectOffset(s);
d.style.left=O.x+'px';
d.style.top=(O.y-(extra?45:30))+'px';
}


var W=getWindowSize();
if((d.offsetLeft+d.offsetWidth)>W.wx)
d.style.left=W.wx-d.offsetWidth-30;

if(under)
d.style.top=(O.y+20)+'px';
}
function getObjectOffset(o){

var x=y=0;
do{
x+=o.offsetLeft;
y+=o.offsetTop;

if(o.id=='noteTable'){

x-=gel('emailDIV').scrollLeft;
y-=gel('emailDIV').scrollTop;
}
}while(o=o.offsetParent);

return{x:x,y:y};
}
function getOffsetTop(o){

alert('use getObjectOffset(o).y!');
var y=0;
while(o){
y+=o.offsetTop;
o=o.offsetParent;
}
return y;
}





var floatLast=0;
function floatClean(n){
debug('fC('+n+')');
var f;
fH();
if(!n){
gel('floater').innerHTML=
gel('floater2').innerHTML=
gel('floater3').innerHTML='';
}else{
gel('floater'+n).innerHTML='';
}

if(f=gel('hiddenFrame'))
f.src='i/1.gif';
}
fC=floatClean;

function floatHide(n){
debug('floatHide('+n+')');
floatLast=-1;
if(!n||n==1){

if(gel('floater'))
gel('floater').style.display=
gel('floater2').style.display=
gel('floater3').style.display=
gel('blanket').style.display='none';
return;
}

try{
gel('floater'+n).style.display=
gel('blanket').style.display='none';
}catch(e){
debug(e+'\n'+stackTrace());
}
}
fH=floatHide;

function floatShow(n){

n=(!n||n==1)?'':n;
gel('floater'+n).style.display='';
}

function floatError(msg,clk,caller){
fH();

if(msg.name){
var tmp=msg.name+'<br/>'+
msg.message+'<br/>';
try{
if(msg.stack){
var S=msg.stack.split('\n');
for(var i=0;i<S.length;i++){
if(S[i].length>100)
S[i]=S[i].substring(0,100)+'...'+S[i].substring(S[i].lastIndexOf(':'));
tmp+='<nobr>'+S[i]+'</nobr><br/>\n';
}
}
else if(msg.fileName)
tmp+=msg.fileName+':'+msg.fileNumber+'<br/>';
}catch(e){}
msg=tmp;
}else{
msg=''+msg;
}

if(caller){
msg+='caller '+stackTrace(caller);
}

ckajax.getText('error.php','msg='+escape(msg)+'&trace=',function(stat,statStr,resp){

});

if(msg.indexOf('Logged out')!=-1)
return showLogin(wtext('logBackIn'));

var clk='fH();'+(clk==null?'':clk);
if(msg.indexOf('not been verified')!=-1)
clk='fH();logout()';

if(msg=='')msg='Please try again later';
floatPopover('There was an error',msg,[button('Close',clk)]);
}
function floatNotice(msg,clk){

fH();
var txt='Close';
if(clk==null)
clk='';
else
txt='Back';
floatPopover('Notice',msg,
[button(txt,'fH();'+clk)],
2);
}
function floatAsk(tit,msg,but,n){
debug('floatAsk()');
floatPopover(tit,msg,but,n);
}

function floatDone(msg,time){

if(time==null)
time=2500;
floatPopover('&nbsp;',msg,[button('Close','fH()')]);
setTimeout(fH,time);
}


var floatProgress_t=250;
function floatProgress(msg){

if(!msg)
msg='Processing...';
floatLast=utime();
floatHide();
blanketScreen();
setTimeout('floatProgress2(\''+escape(msg)+'\')',floatProgress_t);
}
function floatProgress2(msg){

if(floatLast==-1)
return;
if((utime()-floatLast)>=(floatProgress_t-100))
floatPopover('&nbsp;',unescape(msg),null,2);
}

function blanketScreen(){

var b=document.body,
o=7,
s=gel('blanket').style,
w=getWindowSize();
s.position='absolute';
s.display='';
s.opacity=o/10;
s.filter='alpha(opacity='+o*10+')';
s.left=0;
s.top=0;

s.height=w.ty+'px';
s.width='100%';
}

function floatPopover(tit,msg,but,num){

floatLast=utime();
var fltr=gel('floater');
if(num==2)fltr=gel('floater2');
if(num==3)fltr=gel('floater3');

if(!fltr){
debug('floatPopover()fltr==null');
return setTimeout(function(){floatPopover(tit,msg,but,num);},1000);
}
try{
floaterSetStyle(fltr.style);

var buthtml=popInput(but);
}catch(e){
return alert('floatPopover ex\n'+e.message+'\n'+fltr+'\n'+stackTrace());
}

if(!tit)tit='';

blanketScreen();
fltr.innerHTML=wtext('popover.html',{
POPOVERID0:floatPopoverId(num,0),
POPOVERID1:floatPopoverId(num,1),
MSG:msg,
TITLE:tit,
BUTHTML:buthtml
});

floaterCentre(fltr);
}

function floatPopoverId(a,b){

return 'id=floatT'+a+b;
}


function popInput(arr){

if(!arr||arr.length==0)
return '';
var ret='<span class=popInput><table width=100%><tr>';
for(var i=0;i<arr.length;i++)
ret+='<td align=center>'+arr[i]+'</td>';
ret+='</tr></table></span>';
return ret;
}

var floatZ=1;
function floaterSetStyle(s){

s.display='';
s.backgroundColor='transparent';
s.left='100px';
s.top='100px';
s.border='none';
s.zIndex=floatZ++;
}

function floaterCentre(el){

var s=el.style,
win=getWindowSize(),
b=document.body;
s.zIndex=floatZ++;
s.position='absolute';
var l=Math.floor((win.wx-el.offsetWidth)/2)+win.sx,
t=Math.floor((win.wy-el.offsetHeight)/2)+win.sy;
s.left=(l<10?10:l)+'px';
s.top=(t<10?10:t)+'px';
debug('floaterCentre el='+el.id+
' offset=['+el.offsetWidth+','+el.offsetHeight+']'+
' scroll=['+win.sx+','+win.sy+']'+
' win=['+win.wx+','+win.wx+']'+
' final=['+s.left+','+s.top+']');

blanketScreen();
}


function resizeFloater(n,w,h){

n=(!n||n==1)?'':n;
var f=gel('floater'+n);
if(!f)
return;


var s=f.style;
s.width=w+'px';
s.height=h+'px';


var fn='floatT'+n,
t=[gel(fn+'0').style,gel(fn+'1').style];
for(var i=0;i<t.length;i++)
t[i].width=t[i].height='100%';

window.scroll(0,0);
floaterCentre(f);
}


function getWindowSize(){

var d=document,
w=window,
px,py,tx,ty,sx,sy,
b=d.body,
e=d.documentElement;

if(!b)alert(stackTrace());

if(w.innerWidth){
px=w.innerWidth;
py=w.innerHeight;
}else{
var e=d.documentElement;
px=e&&e.clientWidth?e.clientWidth:b.clientWidth;
py=e&&e.clientHeight?e.clientHeight:b.clientHeight;
}



if(w.innerHeight&&w.scrollMaxY){
tx=w.innerWidth+w.scrollMaxX;
ty=w.innerHeight+w.scrollMaxY;
}
else if(b.scrollHeight>b.offsetHeight){
tx=b.scrollWidth;
ty=b.scrollHeight;
}
else{
tx=b.offsetWidth+b.offsetLeft;
ty=b.offsetHeight+b.offsetTop;
}
if(e.clientHeight>ty){
ty=e.clientHeight;
}

if(typeof(w.pageYOffset)=='number'){
sx=w.pageXOffset;
sy=w.pageYOffset;
}else if(b&&(b.scrollLeft||b.scrollTop)){
sx=b.scrollLeft;
sy=b.scrollTop;
}else if(e&&(e.scrollLeft||e.scrollTop)){
sx=e.scrollLeft;
sy=e.scrollTop;
}else{
sx=d.scrollLeft;
sy=d.scrollTop;
}
if(!sx)
sx=0;
if(!sy)
sy=0;

return{wx:px,wy:py,tx:tx,ty:ty,sx:sx,sy:sy};
}

function isDSTNow(){

return(new Date()).getTimezoneOffset()==(new Date('2009/07/01')).getTimezoneOffset();
}
function isDSTZone(){

return(new Date('2009/07/01')).getTimezoneOffset()!=(new Date('2009/12/31')).getTimezoneOffset();
}
function drawClock(off){
if(!drawClock.n)drawClock.n=1;


if(off=='gmt')off=0;
if(off=='eastern')off=-5;
if(off=='central')off=-6;
if(off=='mountain')off=-7;
if(off=='pacific')off=-8;
if(isDSTZone())off+=0;
if(isDSTNow())off+=1;
debug('drawClock('+off+')dstZone='+isDSTZone()+' dstNow='+isDSTNow()+' tzOff='+tzOffset());
var sec='';
if(off*-60*60!=tzOffset())
sec='noSeconds';
if(_IE)
sec='noSeconds';
var html='<canvas style="width:40px;height:40px" id="drawClock'+drawClock.n+'" class="CoolClock::20:'+sec+':'+off+'"></canvas>';

drawClock.n++;

return html;
}




function logout(skipCookies,skipHome){

wxpauth=''; 

window.onkeypress=noop;

var e;
if(e=gel('sysadmin'))
e.innerHTML='';



if(wxptrial||getCookie('wxpsuper')!=''){
wxpemail='';
}
ckajax.getText(base('logout=1'),'logout=1');

if(!skipCookies){
setCookie('wxpauth=');
setCookie('wxpsuper=');
}

if(!skipHome)
gotoPage('home');
}

function showCurrentTime(){
var t='autologout.';

if(wxpauth=='')return;

if(wxpauth!=''&&inactiveLogout()){
fH();
logout(false,true);
return floatAsk(wtext(t+'title'),wtext(t+'body'),
[button(wtext('close'),'fH();gotoPage(\'home\')')]);
}

if(otherLogin()){
t='otherLogin.';
fC();
window.onkeypress=noop;
return floatAsk(wtext(t+'title'),wtext(t+'body'),
[button(wtext('close'),'gotoPage(\'home\')')]);
}


var newauth=getCookie('wxpauth');
if(newauth&&newauth!=wxpauth)
wxpauth=newauth;


if(!autologout_shown&&wxpauth!=''&&inactiveFor()+60>SYSINFO['session.timeout.mins']*60){
fH();
floatAsk(wtext(t+'warn.title'),
wtext(t+'warn.body',{MINS:SYSINFO['session.timeout.mins']}),
[button(wtext('resume'),'fH(3);wxpRefresh();')],
3);


window.onkeypress=wxpRefresh;
autologout_shown=true;
}

setTimeout(showCurrentTime,1000);
}

function showLoginInfo(){

F=function(i,h){if(o=gel(i))o.innerHTML=h};
F('loginIP',login.now.ip);
F('loginTime',gmt2local(login.now.date));
F('lastLoginIP',login.last.ip);
F('lastLoginTime',gmt2local(login.last.date));

gel('accountEmail').innerHTML=login.now.email;
gel('accountName').innerHTML=login.now.name;
}

function agreeTAC(){

var email=unescape(getCookie('wxpemail')).toLowerCase();
if(email.indexOf(DOMAIN)!=-1)
email='';

window.scroll(0,0);

fH();
var t='agreeTAC.',
html=wtext(t+'html');
floatAsk(wtext(t+'title'),html,
[button(wtext(t+'declineButton'),'fH();logout()'),
button(wtext(t+'agreeButton'),'agreeTACDo()','signupSubmit')]
);
postmarkTACWatcher(true);
}

function agreeTACDo(){

fH();
var data='agreeTAC=1'+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error:')!=-1)
alert(resp);
showMain();
});
}

function showSignup(){

var email=unescape(getCookie('wxpemail')).toLowerCase(),
name=unescape(getCookie('wxpemail')).toLowerCase(),
idx=name.indexOf(' '),
fname=name.substr(0,idx),
lname=name.substr(idx);
if(email.indexOf(DOMAIN)!=-1)
email='';

window.scroll(0,0);

fH();
blanketScreen();
var t='signup.';
floatAsk('Sign up',
wtext(t+'html',{EMAILval:email}),
[button(wtext('close'),'fC();gotoPage(\'home\')'),
button(wtext('next'),'signupDo()','signupSubmit')]
);
if(getCookie('wxpjoinus')==1){
var e=gel('email');
e.disabled=true;
e.className='iTextDis';
}
postmarkTACWatcher(true);

changeCountry();

var d=unescape(getCookie('wxpsignupdata'));
if(d!=''){
var R=parseResponse(d);
R=R.data[0];
gel('email').value=b64dec(R.email);
gel('firstname').value=b64dec(R.firstname);
gel('lastname').value=b64dec(R.lastname);
gel('address').value=b64dec(R.address);
gel('address2').value=b64dec(R.address2);
gel('city').value=b64dec(R.city);
gel('postalcode').value=b64dec(R.postalcode);
var c=b64dec(R.country);
setSelected('country',c);
if(getSelected('country')!=c){
gel('country').options[gel('country').options.length]=new Option(countries[c],c,true);
gel('country').onchange();
}
setSelected('province',b64dec(R.province));
}

setTimeout(function(){gel('firstname').focus()},500);
}

function signupWatcher(){
var MIN=6,
str=gel('pswdStrength');
if(!str)return;

var pswd=gel('newpswd').value,
l=pswd.length;
if(l>MIN)l=MIN;
str.innerHTML=parseTmpl('<span style="border:1px solid #000000;background:{BG}"><img src=i/1.gif height=1 width={W}/></span>'+
'<span style="border:1px solid #000000"><img src=i/1.gif height=1 width={Wi}/></span>'+
'&nbsp;{LEN}/{REQ}',
{BG:(l<MIN?'#ed1c24':'#0067ac'),
W:l/MIN*100,
Wi:(MIN-l)/MIN*100,
LEN:pswd.length,
REQ:MIN});

setTimeout(signupWatcher,'250');
}

function signupDo(){
debug('signupDo()');
var tac=getCheckedValue(gel('tac_agree').form.tac_agree),
e=gel('email'),
fn=gel('firstname'),
ln=gel('lastname'),
c=gel('city'),
pv=gel('province'),
cy=gel('country'),
p=gel('newpswd'),
p2=gel('newpswd2'),
ss='signupSubmit',
err=gel('signupMsg'),
errFcn=function(o,msg){
enableButton(ss);
postmarkTACWatcher(true);
err.innerHTML=wtext(msg);
cFH(o);
},
v,
t='signup.error.';

postmarkTACWatcher_run=false;
disableButton(ss);
err.innerHTML='';

v=e.value;
if(v.length==0||v.indexOf('@')==-1)return errFcn(e,t+'bademail');

v=fn.value;
if(v.length <2)return errFcn(fn,t+'shortname');

v=ln.value;
if(v.length <2)return errFcn(ln,t+'shortname');

v=c.value;
if(v.length <3)return errFcn(c,t+'shortcity');

v=getSelected(cy.id);
if(v.length <2)return errFcn(cy,t+'nocountry');

v=getSelected(pv.id);
if(v.length <2)return errFcn(pv,t+'noprovince');

if(p.value.length <6)return errFcn(p,t+'weakpswd');
if(p.value!=p2.value)return errFcn(p2,t+'pswdmatch');

if(tac!='agree')return errFcn(gel('tac_agree'),t+'terms');

floatProgress(wtext('loading'));

var data='signup=1'+
'&firstname='+escape(fn.value)+
'&lastname='+escape(ln.value)+
'&country='+escape(cy.value)+
'&province='+escape(pv.value)+
'&city='+escape(c.value)+
'&address='+escape(gel('address').value)+
'&address2='+escape(gel('address2').value)+
'&postalcode='+escape(gel('postalcode').value)+
'&phonenum='+escape(gel('phonenum').value)+
'&email='+escape(e.value)+
'&password='+escape(p.value)+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error:')!=-1){
fH();
blanketScreen();
floatShow(1);
enableButton(ss);
postmarkTACWatcher(true);

return err.innerHTML=resp;
}

setCookie('wxpjoinus=');
if(resp.indexOf('wxpauth=')!=-1){
fH();
wxpauth=resp.split('=')[1];
return gotoPage('reg');
}else{
fH();
var t='confirmPending.';
floatAsk(wtext(t+'title'),
wtext(t+'body',{EMAIL:e.value,WXPNANE:SYSINFO.name}),
[button(wtext('ok'),'gotoPage(\'home\');')]
);
}
});
}

function showLogin(msg){

var E=gel('email'),
P=gel('password'),
email=wxpemail?wxpemail:unescape(getCookie('wxpemail')).toLowerCase();

if(!E&&!P){
E=gel('loginemail');
P=gel('loginpassword');
}
if(E&&P){
if(email){
mainFocus(E);
E.value=email;
}
else if(!E.touch)return mainFocus(E);
if(!P.touch)return mainFocus(P);
return loginDo();
}

if(URL.indexOf('?reg')==-1)
return gotoPage('reg');

setCookie('wxpauth=');
wxpauth='';

if(email.indexOf(DOMAIN)!=-1)
email='';

msg=msg?msg:'';

floatAsk('Login',wtext('login.html',{EMAIL:email,ERRMSG:msg}),[]);

if(!E)E=gel('email');
if(!P)P=gel('password');
if(email==''){
if(E)E.focus();
}else{
if(P)P.focus();
}
}

function requestConfirmEmail(emailArg,fcnstr){

if(!emailArg)
emailArg=wxpemail;
if(!fcnstr)
fcnstr='fH()';

var t='confirmPending.sent.',
data='requestConfirmEmail=1'+
'&email='+emailArg+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
fH();
floatAsk(wtext(t+'title'),
wtext(t+'body',{EMAIL:emailArg}),
[button(wtext('next'),fcnstr)]
);
});
}

function gotoUrl(url){

document.location.href=url;
}

function gotoHome(){
gotoPage('home');
}
function gotoPage(page){

var idx;
url=BASEURL;
if((idx=url.indexOf('?'))!=-1)
url=url.substr(0,idx);
if((idx=url.indexOf('#'))!=-1)
url=url.substr(0,idx);
gotoUrl(url+'?'+page);
}
function verisignPopup(){
window.open('https://seal.verisign.com/splash?form_file=fdf/splash.fdf&dn=WWW.TRUSTIFI.COM&lang=en',
'VRSN_Splash',
'location=yes,status=yes,resizable=yes,scrollbars=yes,width=560,height=500');
}

function loginDo(){

var em=getVal('email'),
pw=getVal('password'),
re=getVal('remember'),
M=gel('loginMsg');
if(em==''){
em=getVal('loginemail');
pw=getVal('loginpassword');
}

em=em.toLowerCase();
wxpemail=em.toLowerCase();

M.style.color='#ffffff';
M.innerHTML=wtext('login.loading');

disableButton('loginButton');
var t='login.error.',
data='login=1'+
'&remember='+escape(re)+
'&email='+escape(em)+
'&password='+escape(pw);
ckajax.getText(base(data),data,function(stat,statStr,resp){
wxpemail=getCookie('wxpemail');

M.style.color='#ff0000';
if(stat==500){
enableButton('loginButton');
return M.innerHTML='Please try again later';
}
if(resp.indexOf('Error: Log in failed')!=-1){
enableButton('loginButton');
return M.innerHTML=wtext(t+'failed');
}
else if(resp.indexOf('Error: Pending account')!=-1){
enableButton('loginButton');
return M.innerHTML=wtext(t+'createAccount');
}
else if(resp.indexOf('Error: Not verified')!=-1){
enableButton('loginButton');
return M.innerHTML=wtext(t+'notVerified',{EMAIL:em});
}
else if(resp.indexOf('Error:')!=-1||resp==''){
enableButton('loginButton');
return M.innerHTML=resp+wtext(t+'suffix');
}
wxpauth=resp;

fH();
gotoPage('reg');
});
}




function showTrialLogin(){

var t='trialAccount.login.';
floatAsk(wtext(t+'title'),
wtext(t+'body'),
[button(wtext('cancel'),'logout();floatHide()'),
button(wtext(t+'okButton'),'fH()'),
button(wtext('next'),'logout(false,true);gotoSignup()')]
);
}
function showTrialAddPart(){

var t='trialAccount.addPart.';
floatAsk(wtext(t+'title'),
wtext(t+'body'),
[buttonCancel(),
button(wtext('next'),'logout(false,true);gotoSignup()')]
);
}
function showTrialAddPostmark(tag){

var t='trialAccount.postmark.';
fH();
floatAsk(wtext(t+'title'),
wtext(t+'body'),
[buttonCancel(),
button(wtext('next'),'logout(false,true);gotoSignup()')]
);
}

function forgotPassword(){

var em=gel('email');
if(!em)
em=gel('loginemail');
em=em.value;

wxpemail=em.toLowerCase();

var M=gel('loginMsg').pointer='progress';
M.innerHTML=wtext('login.forgot.loading');
var data='forgotPassword=1'
+'&email='+escape(em)
+'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error:')==0)
return gel('loginMsg').innerHTML=resp+wtext('login.error.suffix');
gel('loginMsg').innerHTML=wtext('login.forgot.done');
});
}

function showMain(fromLogin){
debug('showMain(fromLogin)');
tree_loadData(function(){
showCurrentTime();
if(wxptrial)
showTrialLogin();


var O=getCookie('wxpop');
if(O!=''){
O=unescape(O).split(':');

if(O[0]=='askClerkConfirm')askClerkConfirm(O[1],O[2]);
else if(O[0]=='showFile')showFileJump(O[1]);
else if(O[0]=='showEpmHtml')showEpmHtml(O[1]);
else if(O[0]=='floatError')floatError(b64dec(O[1]));
else alert(print_r(O));
setCookie('wxpop=','');
}


});
}

function showEpmHtml(L,key,action) {
  L.oldonclick = L.onclick;
  L.onclick = noop;

  L.href = SYSINFO.appurl +'?wxpauth='+ wxpauth +'&showEpmHtml='+key +'&'+action;
  L.click();

  L.onclick = L.oldonclick;
  L.href = '#';
}

























function createGroup(){

var t='createGroup.';
floatAsk(wtext(t+'title'),
wtext(t+'body',{GROUPNAME:''}),
[buttonCancel(),button(wtext('next'),'createGroupDo()')]
);
gel('groupName').focus();
}

function createGroupDo(){

var gn=getVal('groupName'),
data='createGroup='+escape(gn)
+'&wxpauth='+wxpauth;
floatProgress();
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error: ')!=-1)
return floatError(resp);
setwxpview('');
wxpRefresh(function(){
var G=profile.groups;
for(var i=0;i<G.length;i++)
if(gn==G[i].name)
showGroupAdmin(G[i].id);
fH();
});
});
}

function editProfileCheckEmailInform(e,fcnstr){

var t='editProfile.checkEmailInform.';
fH();
blanketScreen();
var html=wtext(t+'body',{EMAIL:e});
floatAsk(wtext(t+'title'),
html,
[button(wtext('close'),'fH();'+fcnstr)],
2
);
}

function editProfileChangeEmailInform(){

return;
var t='editProfile.changeEmailInform.';
fH();
blanketScreen();
floatAsk(wtext(t+'title'),
wtext(t+'body'),
[button(wtext('next'),'fH(2);blanketScreen();floatShow(1);')],
2
);
}

function editProfile(mod){

qTrBg=['#ffffff','#f2f2f2'];qTrN=0;

mod=mod?mod:'';

var p=[];
for(var k in profile)
p[k]=mod==''?profile[k]:'';

if(mod!=''){
p.country='VVM='; 
}

if(!login||!login.now)
return;

var t='editProfile.',
submit=mod==''?'editProfileDo':'createUserDo',
emailHtml=
'<span id=emailHidden style="display:none">'+iText('email',login.now.email)+'</span>'+
'<span id=emailShown>'+login.now.email+'&nbsp;('+iLink('toggleHidden(\'email\',editProfileChangeEmailInform)','Change')+')</span>',
html=wtext(t+'html');
html=parseCounter(strReplace(html,'{QTRBGN}','{QTRBG{**N:2}}'));
html=parseTmpl(html,{
SUBMIT:submit,
FIRSTNAME:b64dec(p.firstname),
LASTNAME:b64dec(p.lastname),
EMAILHTML:mod==''?emailHtml:iText('email',''),
ADDRESS:b64dec(p.address),
ADDRESS2:b64dec(p.address2),
CREDITGROUP:p.creditgroup,
CITY:b64dec(p.city),
POSTALCODE:b64dec(p.postalcode),
PHONENUM:b64dec(p.phonenum),
QTRBG0:'#ffffff',
QTRBG1:'#f2f2f2'
});

fC();
if(mod=='createUser.fillProfile')
t='createUser.ask.';
var B=[buttonCancel(),buttonS(null,null,'editProfileForm')];

floatAsk(wtext(t+'title'),html,B);

if(mod=='createUser.fillProfile'){
gel('modHide1').style.display='none';
gel('creditgroupRow').style.display='none';
}
if(gel('getpostmarkemail'))gel('getpostmarkemail').checked=p.getpostmarkemail==1;

setDropDown('country',b64dec(p.country));
changeCountry();
setDropDown('province',b64dec(p.province));
setDropDown('creditgroup',p.creditgroup);

gel('firstname').focus();
purchaseCreditsWatcher();
}

function askClerk(){

var t='askClerk.';
fH();
floatAsk(wtext(t+'title'),
wtext(t+'body',{}),
[buttonCancel(),
button(wtext('next'),'askClerkDo()')]
);
var e=gel('email');
e.value='';
e.focus();
}
function askClerkDo(){

var t='askClerk.do.',
email=getVal('email'),
data='askClerk='+escape(email);
floatProgress();
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
fH();
floatAsk(wtext(t+'title'),
wtext(t+'body',{EMAIL:email}),
[button(wtext('close'),'fH()')]
);
});
}

function askClerkConfirm(cnf,email){

askClerkConfirm.info={CONF:cnf,EMAIL:email};
var t='askClerk.conf.',
C=b64dec(cnf).split(',');
floatAsk(wtext(t+'title'),
wtext(t+'body',{CONF:cnf,EMAIL:email}),
[buttonCancel(),
button(wtext(t+'agree'),'askClerkConfirmDo()')]
);
}
function askClerkConfirmDo(){

var t='askClerk.done.',
data='askClerkConfirm='+askClerkConfirm.info.CONF
+'wxpauth='+wxpauth;
floatProgress();
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error:')!=-1)
return floatError(resp);
fH();
floatAsk(wtext(t+'title'),
wtext(t+'body',{EMAIL:askClerkConfirm.info.EMAIL}),
[button(wtext('close'),'fH()')]
);
});
}

function deactivateAccount(){

var t='deactivateAccount.';
fH();
floatAsk(wtext(t+'title'),
wtext(t+'body',{EMAIL:wxpemail}),
[button(wtext('cancel'),'editProfile()'),
button(wtext(t+'submit'),'deactivateAccountDo()')]
);
}

function deactivateAccountDo(){

var t='deactivateAccount.done.',
data='deactivateAccount=1'
+'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error')!=-1)
floatError(resp);
floatAsk(wtext(t+'title'),
wtext(t+'body',{EMAIL:wxpemail}),
[button(wtext('close'),'logout()')]
);
});
}

function editProfileDo(){

var msg=gel('editProfileMsg'),
op=gel('oldpswd'),
p=gel('newpswd'),
p2=gel('newpswd2'),
t='editProfile.';

if(p.value!=''){
if(op.value==''){
msg.innerHTML=wtext(t+'error.oldpswd');
return op.focus();
}
if(p.value!=p2.value){
msg.innerHTML=wtext(t+'error.pswdmatch');
return p2.focus();
}
}

if(purchaseCreditsCheckBasic('firstname')||
purchaseCreditsCheckBasic('lastname')||
purchaseCreditsCheckBasic('city'))
return msg.innerHTML;

floatProgress(wtext('loading'));

var data='editProfile=1'
+'&email='+escape(getVal('email'))
+'&oldpswd='+escape(op.value)
+'&newpswd='+escape(p.value)
+'&firstname='+escape(getVal('firstname'))
+'&lastname='+escape(getVal('lastname'))
+'&address='+escape(getVal('address'))
+'&address2='+escape(getVal('address2'))
+'&city='+escape(getVal('city'))
+'&province='+getSelected('province')
+'&country='+getSelected('country')
+'&postalcode='+escape(getVal('postalcode'))
+'&phonenum='+getVal('phonenum')
+'&getpostmarkemail='+getCheckedValue('getpostmarkemail')
+'&creditgroup='+getSelected('creditgroup')
+'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error:')!=-1){
fH();
blanketScreen();
floatShow(1);
return msg.innerHTML=resp;
}
tree_loadData(function(){
if(getVal('email')!=login.now.email){
editProfileCheckEmailInform(getVal('email'),'floatDone(wtext(\''+t+'done\'))');
}else{
floatDone(wtext('editProfile.done'));
}
});
});
}




function showAccountBalance(){

account.personalCentCredits=account.groupCentCredits=0;
if(epmCredits==null)
epmCredits=[];

var CG=profile.creditgroup *=1;

for(var i=0;i<epmCredits.length;i++){
var c=epmCredits[i];
if(c.groupid!=0){
if(c.groupid==CG)
account.groupCentCredits+=c.quantity-c.consumed;
}
else if(c.userid==getUserId()){
account.personalCentCredits+=c.quantity-c.consumed;
}
}
var o=gel('creditBalance');
o.innerHTML=account.personalCentCredits/100;
o=gel(o.id+'Span');
o.style.textDecoration=CG==0?'underline':'none';
o.onmouseover=function(){
var ftxt='Personal credits';
if(!CG)ftxt='Priority credits from '+bold(wxpemail);
floatNearShow(this.id,ftxt,1);
}

o=gel('creditBalanceGroupSpan');
o.innerHTML='';
o.style.textDecoration='none';


var gname='',G=getGroupById(profile.groups,CG);
if(G.id==-1)CG=profile.creditgroup=0;
else gname=stripHTML(G.name);
if(CG){
o.style.textDecoration='underline';
o.innerHTML=truncText(gname,15)+': '+(account.groupCentCredits/100)+'<br/>';
}
o.onmouseover=function(){
var ftxt='Not using group credits';
if(CG)ftxt='Priority credits from '+bold(gname);
floatNearShow(this.id,ftxt,1);
}
}


function showEmailTabHeaders(what){
debug('showEmailTabHeaders('+what+')'+stackTrace());
if(!gel('creditsViewRow'))
return debug('showEmailTabHeaders()not in normal view');

var was=gel('creditsViewRow').style.display=='',
sel=gel('searchSel'),
eth=gel('emailsTabHead'),
D=function(ids,v){
var A=[],ids=ids.split(',');
for(var i=0;i<ids.length;i++)
A[i]=gel(ids[i]);
for(var i=0;i<A.length;i++)
A[i].style.display=v?'':'none';
};

eth.style.cursor='default';
D('checkallSpan,searchViewRow,searchViewSpan,searchViewText,searchViewSwitch,advSearchViewText,advSearchViewSpan,advSearchViewSwitch,advSearchViewEnd,emailsViewSpan,creditsViewRow,creditsTabHead',0);
sel.style.width=sel.style.height='12px';

if(what=='EMAIL'){
D('checkallSpan',1);
sel.disabled=false;
D('searchViewRow,searchViewText,searchViewSwitch,emailsViewSpan,emailsTabHead',1);
eth.style.cursor='pointer';
}
else if(what=='SEARCH'){
if(was)gel('emailDIV').innerHTML='';
tree_sel(null);
D('searchViewRow,searchViewSpan,searchViewText,searchViewSwitch,emailsTabHead',1);
}
else if(what=='ADVSEARCH'){
if(was)gel('emailDIV').innerHTML='';
tree_sel(null);
D('advSearchViewSpan,advSearchViewText,advSearchViewSwitch,advSearchViewEnd,searchViewRow,emailsTabHead',1);
}
else if(what=='CREDITS'){
tree_sel(null);
D('emailsTabHead',0);
D('creditsViewRow,creditsTabHead',1);
}
}

function editRefillCredits(cid){
var t='editRefillCredits.',
C=getCreditById(cid),
cards={VISA:'Visa',MC:'MasterCard'},
year=(new Date()).getFullYear(),
html=wtext(t+'body');
level=Math.floor(C.quantity/100 * 0.1)+1,
SC=SYSINFO['credit.schedule'];

if(SC[C.quantity/100])
level=SC[C.quantity/100].level;

html=parseCounter(strReplace(html,'{QTRBGN}','{QTRBGn{**N:2}}'));

var c4=C.refillcardnum4;
c4=c4=='NONE'?'':'XXXX-XXXX-XXXX-'+c4;
html=parseTmpl(html,{
ID:cid,
ACCOUNT:(C.groupid==0?'personal':getGroupById(profile.groups,C.groupid).name),
CARDTYPES:dropDownArr('cardtype',cards,0,0,0,1),
EXPDATE:dropDown('cardexpmm',1,12)+'-'+dropDown('cardexpyyyy',year,year+10),
CARDNAME:b64dec(C.name),
CARDNUM:c4,
PRICE:dec2(C.price),
CREDITS:dec2(C.quantity),
CREDITS_LEVEL:level,
BALANCE:dec2(C.quantity-C.consumed),
ADDRESS:b64dec(C.address),
ADDRESS2:b64dec(C.address2),
CITY:b64dec(C.city),
PROVINCE:C.province,
COUNTRY:C.country,
POSTALCODE:b64dec(C.postalcode),
PHONENUM:b64dec(C.phonenum),
QTRBGn0:'#ffffff',
QTRBGn1:'#f2f2f2'
});

floatAsk('Modify Credit Block Replenishment',
html,
[buttonCancel(),button(wtext('next'),'editRefillCreditsDo('+cid+')')]
);

gel('cardnum').onfocus=function(){
var o=gel('cardnum');
o.value='';
o.noX=true;
o.onfocus=noop();
}
gel('lowaction_notify').checked=C.alarmrefill==0;
gel('lowaction_refill').checked=C.alarmrefill!=0;
setSelected('lowaction_refillquant',C.alarmrefillamount/100);

setDropDown('country',C.country);
changeCountry();
setDropDown('province',C.province);
setDropDown('cardexpyyyy',C.cardexpyyyy);
setDropDown('cardexpmm',C.cardexpmm);

purchaseCreditsWatcher(cid);
purchaseCreditsWatcher2(cid);
}

function editRefillCreditsDo(cid){
var lowaction=gel('lowaction_refill').checked?'refill':'notify',
lowaction_refillquant=getSelected('lowaction_refillquant'),
CCC=gel('editRefillCCTab').style.display!='none',
err=gel('purchaseCreditsMsg'),
C=getCreditById(cid),
bal=(C.quantity-C.consumed)/100;
if(CCC&&(purchaseCreditsCheck2()||purchaseCreditsCheck()))return;

var t='editRefillCreditsDo.',
data='editRefillCredits=1'
+'&creditid='+cid
+'&lowaction='+lowaction
+'&lowaction_refillquant='+lowaction_refillquant
+'&editRefillCCC='+CCC
+'&cardtype='+getSelected('cardtype')
+'&cardname='+escape(getVal('cardname'))
+'&cardnum='+getVal('cardnum')
+'&cardexpyyyy='+getSelected('cardexpyyyy')
+'&cardexpmm='+getSelected('cardexpmm')
+'&address='+escape(getVal('address'))
+'&address2='+escape(getVal('address2'))
+'&city='+escape(getVal('city'))
+'&province='+getSelected('province')
+'&country='+getSelected('country')
+'&postalcode='+escape(getVal('postalcode'))
+'&phonenum='+getVal('phonenum')
+'&wxpauth='+wxpauth;

floatProgress(wtext('loading'));
ckajax.getText(base(data),data,function(stat,statStr,resp){
fH();
if(resp.indexOf('Error:')!=-1){
blanketScreen();
floatShow(1);
return gel('purchaseCreditsMsg').innerHTML=resp;
}
floatAsk(wtext(t+'title'),
wtext(t+'body'),
[button(wtext('close'),'fC()')]
);
wxpRefresh(function(){showCreditHistory(1)});
});
}

function showCreditHistory(reset){
floatPopover('&nbsp;',wtext('loading'),null,1);
setTimeout(function(){try{showCreditHistory_(reset)}catch(e){floatError(e)}},100);
}
function showCreditHistory_(reset){




showRegistry();
showEmailTabHeaders('CREDITS');

fH();
if(epmCredits==null)
epmCredits=[];

quicksort(epmCredits,function(a,b){return b.expirydate-a.expirydate;});

var t='showCreditHistory.',
credStart=iCalTime('credit_start','Jan 01 2010'),
credEnd=iCalTime('credit_end','TOMORROW'),
myCredits=0,
spentBlocks=[],
emptyBlocks=[],
html=wtext(t+'head',{});

if(reset){
credStart=(new Date(iCalSet('credit_start','Jan 01 2010'))).getTime()/1000;
credEnd=(new Date(iCalSet('credit_end',iCalToday()))).getTime()/1000;
}
credEnd+=60*60*24-1;


for(var i=0;i<epmCredits.length;i++){
var c=epmCredits[i],
saveqTrN={},
k=0,
group=getGroupById(profile.groups,c.groupid),
F=epmCreditFiles;
if(c.userid!=getUserId())
continue;

if(F)
for(var j=0;j<F.length;j++){
if(credStart <=F[j].created&&
F[j].created <=credEnd&&
F[j].creditid==c.id){
k++;
}
}
if(k==0)emptyBlocks[emptyBlocks.length]=c.id;
else myCredits++;
if(credStart>c.purchasedate||c.purchasedate>credEnd)
continue;

group=(group.id==-1)?'<span style="font-style:italic;color:#cccccc">personal</span>':floatTruncText(group.name,27);

html+=wtext(t+'row',{
ID:c.id,
GROUP:group,
PURDATE:floatTime(c.purchasedate),
EXPDATE:floatExpiryTime(c.expirydate),
CARDNUM:'XXXX-XXXX-XXXX-'+c.cardnum4,
PAID:'$'+dec2(c.price),
CREDITS:c.quantity/100,
BALANCE:(c.quantity-c.consumed)/100
})+'\n';

var html2='';
if(F&&k)
for(var j=0;j<F.length;j++){
var f=F[j];
if(f.creditid!=c.id||
f.created <credStart||
credEnd <f.created)
continue;

var T=parseEmail(f.to.split(';')[0]);
var W=getProjectById(f.projectid),
tohtml=(f.to.length==0)?'':floatEmail(T,25),
proj='';
if(W){
proj='+'+W.name;
var fid=W.folderid;

while(fid>0){
var fld=getFolderById(fid);
proj='-'+fld.name+'<br/>'+proj;
fid=fld.parentid;
}
}

var clk='',
style='',
P=getProjectById(f.projectid);
if(P){
style='cursor:pointer;';
clk='showProject('+P.folderid+','+P.id+',false,'+f.id+')';
}

html2+=wtext(t+'fileRow',{
CLK:clk,
XSTYLE:style,
EPMDATE:floatTime(1*f.postmarkdate),
EPMTRANKEY:f.epmtrankey,
USER:floatUser(f.userid),
TO:tohtml,
PROJECT:!P?'-':floatText(P.name,getTreeViewSimple(P.folderid,P.id)),
SUBJECT:floatTruncText(b64dec(f.name),12),
SIZE:humanSize(f.size),
CREDITS:f.cost/100
})+'\n';

}
html+=html2;


html+='</table></td></tr></table></td></tr>'; 
if((c.quantity-c.consumed)<=c.alarmthreshold||
(c.quantity-c.consumed)<=c.alarmrefill||
c.cardnum4=='TRFI')
spentBlocks[spentBlocks.length]=c.id;
}

if(myCredits==0){
html+='<tr style="background-color:{QTRBGN}">'+
'<td colspan=7>'+wtext(t+'noCredits')+'</td></tr>';
}

html+='<tr>'+
tdS(201)+
tdS(76)+
tdS(76)+
tdS(161)+
tdS(46)+
tdS(51)+
tdS(43)+
'</tr>'+
'</table>';


html=parseCounter(strReplace(html,'{QTRBGN}','{QTRBGn{**N:2}}'));

fC();
gel('emailDIV').innerHTML=html;

for(var i=0;i<epmCredits.length;i++){
var C=epmCredits[i],CR=gel('creditRow'+C.id);
if(CR)CR.style.backgroundColor=(i%2)?'#ffffff':'#f2f2f2';
}




for(var i=0;i<spentBlocks.length;i++){
var id=spentBlocks[i],
R=gel('creditRefill'+id);
R.onmouseover=function(){floatNearShow(this.id,'Auto-Purchase Inactive',1);};
qImgSet(R,'refillOff');
R.onclick='return false';
}

try{
for(var i=0;i<emptyBlocks.length;i++){
var id=emptyBlocks[i];
gel('creditFileSpan'+id).innerHTML='<span style="font-style:italic;color:#cccccc">Unused</span>';
}
}catch(e){}
}

function creditRefillFloat(cid){
var C=getCreditById(cid),left=C.quantity-C.consumed;
floatNearShow('creditRefill'+cid,wtext('showCreditHistory.row.float',{
HIDEREFILL:C.alarmthreshold==0?'':'style="display:none"',
HIDENOTIFY:C.alarmthreshold==0?'style="display:none"':'',
HIDEMODIFY:(C.alarmthreshold>=left||C.alarmrefill>=left)?'style="display:none"':'',
ALARMTH:Math.floor(C.alarmthreshold/100),
ALARMRE:Math.floor(C.alarmrefill/100),
ALARMREA:Math.floor(C.alarmrefillamount/100)
}),1);
}

function creditClick(cid){

var r=gel('creditFileRow'+cid),
s=r.style;
debug('creditClick('+cid+')clk='+r.onclick);
if(r.onclick!=noop)r.onclick=noop;

s.display=s.display==''?'none':'';
}


function creditOver(cid){

var d=gel('creditRow'+cid);
d.onmouseout=function(){creditOut(cid);};
d=d.childNodes;
for(var i=0,n=0;i<d.length;i++){
if(!d[i].innerHTML)
continue;
var add=(d[i].className.indexOf('clickable')!=-1)?' clickable':'';
d[i].className='noteRo1'+add;
}
}


function creditOut(id){

var d=gel('creditRow'+id).childNodes;
for(var i=0,n=0;i<d.length;i++){
if(!d[i].innerHTML)
continue;

var add=(d[i].className.indexOf('clickable')!=-1)?' clickable':'';
d[i].className='noteR1'+add;
}
}

function showAccountDetails(){


tree_unselect();
showCreditHistory();

}

function showCreditsBar(a,b){

var v=Math.floor(100 * (a/b)),
img='<span class="imgProgBarFull" style="width:'+(102-v)+'px"></span>'+
'<span class="imgProgBarEmpty" style="width:'+v+'px"></span>';
if(a==b)
img='<span class="imgProgBarEmpty" style="width:101px"></span>';
return dec2(b-a)+' out of '+dec2(b)+
'</td><td width=100%>'+
img;
}

var purchaseReturn=null;
function purchaseCredits(){

purchaseReturn=null;
var t='purchaseCredits.intro',
items=[],
shelf=SYSINFO['credit.schedule'],
html;
var id,rows='';
for(var k in shelf){
if(k.indexOf('@')==0)
continue;
id='buyepm'+k;
rows+=wtext(t+'.row',{ID:id,VAL:k,PRICEPER:dec2(shelf[k].subtotal/k*100),PRICETOT:dec2(shelf[k].subtotal*100)});
}

var D=[],
G=profile.groups,
dropdown='';
D['0']='Personal';
if(G){
for(var i=0;i<G.length;i++)
D[G[i].id]=G[i].name;
dropdown=wtext(t+'.dropdown',{FORGROUP:wtext(t+'.forGroup'),SELECT:dropDownArr('forGroupSel',D,null,null,false,true)});
}

html=wtext(t+'.tab',{ROWS:rows,DROPDOWN:dropdown});
html=parseCounter(strReplace(html,'{QTRBGN}','{QTRBG{**N:2}}'));
html=parseTmpl(html,{QTRBG0:'#ffffff',QTRBG1:'#f2f2f2'}),

fC();
floatAsk('&nbsp;',
wtext(t,{
CREDITTAB:html,
TERMSURL:SYSINFO.termsurl
}),null,3 
);
window.scroll(0,0);

floaterCentre(gel('floater3'));
purchaseCreditsWatcher();
}

function checkCouponCode(code){

var t='purchaseCredits.couponError.',
data='checkCouponCode='+code+
'&wxpauth='+wxpauth;
resp=ckajax.getText(base(data));
if(resp.indexOf('Error: Invalid coupon')!=-1){
floatAsk(wtext(t+'title'),wtext(t+'body'),
[button(wtext('close'),'fH();purchaseCredits()')],2);
}else if(resp.indexOf('Error: ')!=-1){
floatAsk(wtext(t+'title'),resp,
[button(wtext('close'),'fH();purchaseCredits()')],2);
}else{
var R=parseResponse(resp);
return R.coupon[0];
}

return null;
}

function purchaseCreditsAsk(){

if(wxptrial)
return showTrialAddPostmark();

var couponcode=gel('couponcode'),
cred=gel('buyepm20'),
forGroupSel=getSelected('forGroupSel');

if(cred)
cred=getCheckedValue(cred.form.buyepm);
else
cred=gel('credits').value;

if(cred==''&&(!couponcode||couponcode.value=='')){
var t='purchaseCredits.quantity.';
fH();
return floatAsk(wtext(t+'title'),wtext(t+'body'),[button(wtext('close'),'fH();purchaseCredits()')]);
}

var subtot=SYSINFO['credit.schedule'][cred].subtotal;

if(couponcode&&couponcode.value!=''){
var C=checkCouponCode(couponcode.value);
if(!C)
return;
cred=C.credits;
subtot=dec2(C.price);
}else{
couponcode='';
}

var country=getVal('country',b64dec(profile.country)),
province=getVal('province',b64dec(profile.province)),
t='purchaseCredits.';
replace={
CRED:cred,
FORGROUPSEL:forGroupSel,
COUPONCODE:couponcode,
CARDNAME:getVal('cardname'),
EMAIL:wxpemail,
SUBTOT:subtot,
FIRSTNAME:purchaseCreditsGetVal('firstname'),
LASTNAME:purchaseCreditsGetVal('lastname'),
ADDRESS:purchaseCreditsGetVal('address'),
ADDRESS2:purchaseCreditsGetVal('address2'),
CITY:purchaseCreditsGetVal('city'),
POSTALCODE:purchaseCreditsGetVal('postalcode'),
PHONENUM:purchaseCreditsGetVal('phonenum'),
TERMSURL:SYSINFO.termsurl
};

html=wtext(t+'step2.intro',replace);
html=parseCounter(strReplace(html,'{QTRBGN}','{QTRBG{**N:2}}'));
fC();
floatAsk('&nbsp;',
parseTmpl(html,{QTRBG0:'#ffffff',QTRBG1:'#f2f2f2'}),
null,3
);

setDropDown('country',country);
changeCountry();
setDropDown('province',province);

purchaseCreditsWatcher();
gel('firstname').focus();
floaterCentre(gel('floater3'));

}

function purchaseCreditsGetVal(id,def){

var val=getVal(id);
if(!val){
if(val=profile[id])
val=b64dec(val);
}
if(!val||val=='')
val=profile[id];
if(!val)
val='';

return val;
}

function purchaseCreditsAsk2(){

if(purchaseCreditsCheck())
return;

debug(print_r(SYSINFO['credit.schedule']));
var cred=gel('credits').value,
forGroupSel=getVal('forGroupSel'),
subtot=SYSINFO['credit.schedule'][cred].subtotal,
couponcode=gel('couponcode');
debug('cred='+cred+'  subtot='+subtot);
if(couponcode&&couponcode.value!=''){
var C=checkCouponCode(couponcode.value);
if(!C)return;
cred=C.credits*1;
subtot=dec2(C.price);
}else{
couponcode='';
}

var now=new Date(),
cards={VISA:'Visa',MC:'MasterCard'},
addr2=gel('address2').value,
year=now.getFullYear();

var replace={
EMAIL:wxpemail,
GROUPNAME:forGroupSel==0?'Personal Credits':getGroupById(profile.groups,forGroupSel).name,
CARDTYPES:dropDownArr('cardtype',cards,0,0,0,1),
EXPDATE:dropDown('cardexpmm',1,12)+'-'+dropDown('cardexpyyyy',year,year+10),
FIRSTNAME:gel('firstname').value,
LASTNAME:gel('lastname').value,
ADDRESS:gel('address').value,
ADDRESS2:addr2,
CITY:gel('city').value,
PROVINCE:getSelected('province'),
COUNTRY:getSelected('country'),
POSTALCODE:gel('postalcode').value,
PHONENUMBER:gel('phonenum').value,
CARDNAME:getVal('cardname'),

CREDITS:cred,
CREDITS_LEVEL:SYSINFO['credit.schedule'][cred].level,
COUPONCODE:couponcode,
FORGROUPSEL:forGroupSel,
SUBTOTAL:subtot,
TERMSURL:SYSINFO.termsurl
};
html=wtext('purchaseCredits.step3.intro',replace);
html=parseCounter(strReplace(html,'{QTRBGN}','{QTRBG{**N:2}}'));
html=parseTmpl(html,{QTRBG0:'#ffffff',QTRBG1:'#f2f2f2'});
floatAsk('&nbsp;',html,null,3);

if(addr2!='')
gel('addressBreak').innerHTML='<br/>';

purchaseCreditsWatcher2();
gel('cardname').focus();
gel('cardnum').noX=true;

floaterCentre(gel('floater3'));
}


function changeCountry(){

var c=getSelected('country'),
p=provinces[c];
if(!p)
p={'  ':'Other'};
gel('provinceSpan').innerHTML=dropDownArr('province',p);
}

function purchaseCreditsWatcher(){

if(!gel('address'))return;

checkField(gel('couponcode'),lets+nums+'-.'+' ',12);
checkField(gel('firstname'),lets,30);
checkField(gel('lastname'),lets,30);
checkField(gel('address'),lets,30);
checkField(gel('address2'),lets,30);
checkField(gel('city'),lets,20);
formatPhoneNum(gel('phonenum'));

if(getSelected('country')=='CA'){
gel('postalcode').value=gel('postalcode').value.toUpperCase();
checkField(gel('postalcode'),posts+'-',7);
}
else if(getSelected('country')=='US'){
checkField(gel('postalcode'),nums+' '+'-',10);
}
else{
checkField(gel('postalcode'),posts+' '+'-',10);
}

setTimeout(purchaseCreditsWatcher,250);
}

function purchaseCreditsWatcher2(cid){
var c=gel('credits');
debug('purchaseCreditsWatcher2('+cid+')c0='+c);
if(c&&c.value)c=c.value;
debug('purchaseCreditsWatcher2('+cid+')c1='+c);
if(gel('subtotal')){
debug('purchaseCreditsWatcher2('+cid+')credits='+c);
var st=Math.floor(SYSINFO['credit.schedule'][c].subtotal * 100),
couponcode=gel('couponcode');
if(couponcode&&couponcode.value!=''){
var C=checkCouponCode(couponcode.value);
if(C){
cred=C.credits;
st=C.price*1;
}
}else{
couponcode='';
}
gel('subtotal').innerHTML=dec2(st);


var gst=0;
gst=Math.floor(st * gst);
gel('gst').innerHTML=dec2(gst);


var pst=0;
pst=Math.floor(st * pst);
gel('pst').innerHTML=dec2(pst);

gel('total').innerHTML=dec2(st+pst+gst);
}

var n=gel('cardname');
if(!n)
return;


checkField(n,lets,64);
formatCard(gel('cardnum'));
checkField(gel('cardcvv'),nums,4);
formatPhoneNum(gel('phonenum'));

var e=gel('lowaction_refillquant');
if(e)e.disabled=!gel('lowaction_refill').checked;

setTimeout(function(){purchaseCreditsWatcher2(cid)},250);
}

function formatCard(el){
if(!el)return;
var v=strIsOnly(strReplace(el.value,'-',''),nums+(el.noX?'':'X')),
r='';
if(v.length>0)r+=v.substr(0,4);
if(v.length>4)r+='-'+v.substr(4,4);
if(v.length>8)r+='-'+v.substr(8,4);
if(v.length>12)r+='-'+v.substr(12,4);
el.value=r;
}

function formatPhoneNum(el){
var v=strIsOnly(el.value?el.value:el.innerHTML,nums),
r='';
if(v.length>0)r+=v.substr(0,3);
if(v.length>3)r+='-'+v.substr(3,3);
if(v.length>6)r+='-'+v.substr(6,4);
if(v.length>10)r+='x'+v.substr(10,5);
el.value=r;
}

function validateCard(num){

var parity=num.length%2,
sum=0;
for(var i=0;i<num.length;i++){
var d=parseInt(num.charAt(i));
if(i%2==parity)d=d*2;
if(d>9)d=d-9;
sum+=d;
}
return sum%10==0;
}

function purchaseCreditsCheck(){

var but=gel('nextButton'),
msg=gel('purchaseCreditsMsg');

if(purchaseCreditsCheckBasic('firstname')||
purchaseCreditsCheckBasic('lastname')||
purchaseCreditsCheckBasic('address')||
purchaseCreditsCheckBasic('postalcode')||
purchaseCreditsCheckBasic('city'))
return msg.innerHTML;

if(getSelected('province')==''){
enableButton(but);
cFH(gel('province'));
return msg.innerHTML=wtext('purchaseCredits.error.province');
}

if(getSelected('country')=='CA'){
var val=(o=gel('postalcode')).value;

val=strReplace(strReplace(val,'-',''),' ','');

var err=getSelected('province')!=revpostal['CA'][val.substring(0,1)];

var p=val.split('');


err|=5 <=strIsOnly(p[1]+p[3]+p[5],nums).length;
if(err){
enableButton(but);
cFH(o);
return msg.innerHTML=wtext('purchaseCredits.error.postalcode');
}
}

formatPhoneNum(o=gel('phonenum'));
if(o.value.length <12){
enableButton(but);
cFH(o);
return msg.innerHTML=wtext('purchaseCredits.error.phonenum');
}

return null;
}
function purchaseCreditsCheckBasic(id){

var but=gel('nextButton'),
msg=gel('purchaseCreditsMsg');
t='purchaseCredits.error.';
if(!msg){
msg=gel('editProfileMsg');
t='editProfile.error.';
}

var o=gel(id),
val=getVal(id);
if(o&&val.length <3){
if(but)enableButton(but);
cFH(o);
return msg.innerHTML=wtext(t+id);
}
return null;
}

function purchaseCreditsCheck2(){
var but=gel('purchaseButton'),
msg=gel('purchaseCreditsMsg'),
o,
t='purchaseCredits.error.';

if(checkField(o=gel('cardname'),lets,40)||o.value.length <5){
enableButton(but);
cFH(o);
debug('purchaseCreditsCheck2()a1');
return msg.innerHTML=wtext(t+'cardname');
}

var cardnum=(o=gel('cardnum')).value;
cardnum=strReplace(cardnum,'-','');
if(cardnum.length!=16){
enableButton(but);
cFH(o);
debug('purchaseCreditsCheck2()a2');
return msg.innerHTML=wtext(t+'cardlen');
}

if(cardnum.indexOf('XXXX')!=0){
if(!validateCard(cardnum)){
enableButton(but);
cFH(o);
debug('purchaseCreditsCheck2()a3');
return msg.innerHTML=wtext(t+'badcard');
}
if((getVal('cardtype')=='VISA'&&getVal('cardnum').charAt(0)!='4')||
(getVal('cardtype')=='MC'&&getVal('cardnum').charAt(0)!='5')){
enableButton(but);
cFH(gel('cardtype'));
debug('purchaseCreditsCheck2()a4');
return msg.innerHTML=wtext(t+'cardtype');
}
}

var now=new Date(),
yr=now.getFullYear();
if(1*getSelected('cardexpyyyy')<1*yr||
(getSelected('cardexpyyyy')==yr&&1*getSelected('cardexpmm')<(now.getMonth()+1))){
enableButton(but);
cFH(gel('cardexpmm'));
debug('purchaseCreditsCheck2()a5');
return msg.innerHTML=wtext(t+'cardexp');
}

if((o=gel('cardcvv'))&&o.value.length <3){
enableButton(but);
cFH(o);
debug('purchaseCreditsCheck2()a6');
return msg.innerHTML=wtext(t+'cardcvv');
}

return null;
}

function purchaseCreditsDoErr(but,msg){

fH(2);
blanketScreen();
floatShow(3);
enableButton(but);

if(msg.indexOf('Declined')!=-1)
msg=wtext('purchaseCredits.error.declined');
else if(msg.indexOf('Lost / Stolen')!=-1)
msg=wtext('purchaseCredits.error.loststolen');
if(msg.indexOf('Card Verification')!=-1)
cFH(gel('cardcvv'));

return gel('purchaseCreditsMsg').innerHTML=msg;
}

function purchaseCreditsDo(){

if(purchaseCreditsCheck2())
return;

var but='purchaseButton';

var E=function(s){return escape(s)},
prov=getVal('province'),
lowaction=gel('lowaction_refill').checked?'refill':'notify',
refillquant=getSelected('lowaction_refillquant');
if(lowaction=='refill'&&refillquant=='')
return gel('purchaseCreditsMsg').innerHTML=wtext('purchaseCredits.error.refillquant');

disableButton(but);

if(prov=='')
prov='  ';
var data='purchaseEpmCredits=1'
+'&purnum='+getVal('credits')
+'&couponcode='+getVal('couponcode')
+'&lowaction='+lowaction
+'&lowaction_refillquant='+refillquant
+'&forGroupSel='+getVal('forGroupSel')
+'&firstname='+E(getVal('firstname'))
+'&lastname='+E(getVal('lastname'))
+'&address='+E(getVal('address'))
+'&address2='+E(getVal('address2'))
+'&city='+E(getVal('city'))
+'&province='+prov
+'&country='+getVal('country')
+'&postalcode='+E(getVal('postalcode'))
+'&phonenum='+getVal('phonenum')
+'&cardtype='+getSelected('cardtype')
+'&cardname='+E(getVal('cardname'))
+'&cardnum='+getVal('cardnum')
+'&cardexpyyyy='+getSelected('cardexpyyyy')
+'&cardexpmm='+getSelected('cardexpmm')
+'&cardcvv='+getVal('cardcvv')
+'&wxpauth='+wxpauth;
floatProgress(wtext('purchaseCredits.loading'));

ckajax.getText(base(data),data,function(stat,statStr,resp){
var idx;
if(stat==500){
return purchaseCreditsDoErr(but,'Please try again later');
}
else if((idx=resp.indexOf('Error: '))!=-1){
if(resp.indexOf('9710 Timed out')!=-1)
return purchaseCreditsDoErr(but,wtext('purchaseCredits.error.ccProcess'));
return purchaseCreditsDoErr(but,resp.substr(idx+7));
}
if(resp.length==0)
return purchaseCreditsDoErr(but,'Got empty response from server.<br/>Try again in a few minutes.');

fH();

tree_loadData(function(){
var t='purchaseCredits.done.',
post='fC();showCreditHistory(1);if(purchaseReturn)purchaseReturn();';
var pendingView=0;
for(var i=0;i<filesPending.length;i++){
if(b64dec(filesPending[i].reason).indexOf('No credits found')!=-1){
t='purchaseCredits.viewPending.';
post='fC();showFilesPending()';
}
}
fH();

floatAsk(wtext(t+'title'),
wtext(t+'body'),
[button(wtext('close'),post)]
);
});
});
}

function showWhatIsCVV(){
fH(3);

var t='whatis.cvv.';
floatAsk(wtext(t+'title'),
wtext(t+'body',{TERMSURL:SYSINFO.termsurl}),
[button(wtext('close'),'fH(2);floatShow(3);blanketScreen();')],
2
);
}




var qTrN=0,qTrBg=null;
function qTrjs(A,str){

A.bg=qTrBg[qTrN];qTrN=(qTrN+1)%qTrBg.length;
if(A.err)A.bg='#ff0000';
if(!A.sty)A.sty='';
A.sty+='; background-color:'+A.bg;

return debug('<tr '
+(!A.id?'':' id="'+A.id+'"')
+(!A.sty?'':' style="'+A.sty+'"')
+(!A.clk?'':' onclick="try{'+A.clk+'}catch(e){floatError(e)}"')
+(!A.over?'':' onmouseover="try{'+A.over+'}catch(e){floatError(e)}"')
+(!A.expNote?'':' expNote="'+A.expNote+'"')
+'>'+str+'</tr>');
}


function qTrColour(){

var E=gelt('tr');
for(var i=0;i<E.length;i++){
var d=E[i].childNodes,
cls=E[i].className;
if(!cls||cls.indexOf('noteR')==-1)
continue;


cls=cls.split(' ');
for(var j=0;j<cls.length;j++){
if(cls[j].indexOf('noteR')==0){
cls=cls[j];
break;
}
}

for(var j=0;j<d.length;j++)
if(d[j].innerHTML)
d[j].className=cls;
}
}
function qTrh(a,b,c){

return qTr(bold(a),b,c);
}
function qTr(a,b,c){

qTrN=(qTrN+1)%qTrBg.length;
bg=qTrBg?(' style="background-color:'+qTrBg[qTrN]+'"'):'';
var bsp='';
if(c==null){
c='';
bsp='colspan=2';
}else{
c=td(c);
}
return '<tr'+bg+'>'+td(a)+'<td '+bsp+'>'+b+'</td>'+c+'</tr>\n';
}


function b64hex(s){

var a=b64dec(s),
r='';
for(var i=0;i<a.length;i++){
var v=a.charCodeAt(i);
r+=alphahex.substr(v>>4,1)+alphahex.substr(v&0xf,1);
if((i%12)==11)
r+='<br/>';
else if((i%4)==3)
r+=' ';
}
return r;
}

function endsWith(n,e){

var i=n.toLowerCase().indexOf(e);
if(i==-1)
return false;
return i==n.length-e.length;
}

function iCheck(id,val,txt,clk){

val=val?val:'true';
txt=txt?'<label id="'+id+'_label" for="'+id+'" style="white-space:nowrap">'+txt+'</label>':'';
clk=clk?'onclick="try{'+clk+'}catch(e){floatError(e)}"':'';
return '<input type=checkbox name="'+id+'" id="'+id+'" style="padding:0px" '+clk+' value="'+val+'">'+txt;
}
function iPswd(id,def,size){

if(!size)size='';
else{
size+='';
if(size.indexOf('%')!=-1||size.indexOf('px')!=-1)size='style="width:'+size+'"';
else size='size='+size;
}
var v=getVal(id,def);
debug('iPswd('+id+','+def+','+size+')v='+v);
return '<input class=iText type=password '+size+' id='+id+' name='+id+' value="'+v+'" />';
}
function iText(id,def,size){

if(!size)size='130px';
size+='';
if(size.indexOf('%')!=-1||size.indexOf('px')!=-1)size='style="width:'+size+'"';
else size='size='+size;

var v=getVal(id,def);
debug('iText('+id+','+def+','+size+')v='+v);
return '<input class=iText type=text '+size+' id='+id+' name='+id+' value="'+v+'" />';
}
function iForm(sub,id,targ){

id=id?id:'form1';
targ=targ?'target="'+targ+'"':'';
return '<form id="'+id+'" '+targ+' action="#" method="post" onsubmit="try{'+sub+';}catch(e){floatError(e);}return false">'+
'<input type=image name=iformimg width=1 height=1 src=i/1.gif />';
}
function boxFocus(e,v){
e.style.color='#000000';
if(e.value==v)e.value='';

e.onkeypress=function(ev){
var key;
if(window.event)key=window.event.keyCode;
else if(ev)key=ev.which;
else return true;
if(key==13){
e.form.onsubmit();
return false;
}
return true;
};

e.onblur=function(){
if(e.value==''){
e.value=v;
e.style.color="#cccccc";
}
};
}

function getVal(id,def){

def=def?def:'';
var o=gel(id);
if(!o)
return def;

var v=o.value;
v=!v?o.innerHTML:v;
return(!v||v=='')?def:v;
}

function isMp3File(n){

return endsWith(n,'mp3');
}

function isMusicFile(n){

return(endsWith(n,'mp3')||
endsWith(n,'wmf')||
endsWith(n,'ogg')||
endsWith(n,'wav')||
endsWith(n,'flac')||
endsWith(n,'aiff')||
endsWith(n,'aif'));
}

function isImageFile(n){

return(endsWith(n,'jpg')||
endsWith(n,'jpeg')||
endsWith(n,'gif')||
endsWith(n,'tif')||
endsWith(n,'png'));
}

function isTextFile(n){

return(endsWith(n,'txt')||
endsWith(n,'rtf'))
}

function isSharedFolder(n){

return n==sharedFolder.name;
}

function getImgFromName(n){

n=n.toLowerCase();
if(isSharedFolder(n))return 'open';
if(isImageFile(n))return 'photo';
if(isMusicFile(n))return 'music';
if(isTextFile(n))return 'text';
return 'unknown';
}


function getUserId(auth){

var s=getCookie('wxpsuper');
if(s <0){
setCookie('wxpsuper=');
s=null;
}
if(!wxpauth)wxpauth=getCookie('wxpauth');
auth=auth?auth:wxpauth;
try{
return s?s:unescape(auth).split('|')[1].split(',')[0];
}catch(e){
debug('auth='+auth+' '+getCookie('wxpsuper'));
throw e;
}
}
function getAuthTime(){

if(wxpauth==null||wxpauth=='')
wxpauth=getCookie('wxpauth');
if(wxpauth==null||wxpauth=='')
return 0;
return 1* (unescape(wxpauth).split('|')[1].split(',')[1]);
}
function getwxpview(){

var r=getCookie('wxpview-'+getUserId(wxpauth));
if(r==''){
if((r=getCookie('wxpview-0'))==''){
r='0x0x0x0';
setCookie('wxpview-0=');
}
}
return unescape(r);
}
function setwxpview(v){

return setCookie('wxpview-'+getUserId(wxpauth)+'='+v);
}

function modHide(n,show){
if(n){
var g=gel('modHide'+n);
if(g)g.style.display=show?'':'none';
return;
}

for(var i=1;i<10000;i++){
var g=gel('modHide'+i);
if(!g)break;
g.style.display=show ?'':'none';
}
}
function modShow(n){modHide(n,1);}
function toggleHidden(id,fcn,show){
debug('toggleHidden('+id+','+fcn+')');
var h=gel(id+'Hidden'),
s=gel(id+'Shown');
if(!h&&!s){
h=gel(id);
if(!h)return alert('Cannot find '+id);
h=h.style;
var t=show||h.display=='none';
h.display=t?'':'none';
if(fcn)fcn();
return;
}
if(!h||!s){
h=gel(id);
if(!h)return alert('Cannot find '+id+'Hidden or '+id+'Shown or id');
}

var t=show||h.style.display=='none';
h.style.display=t?'':'none';
if(s)
s.style.display=t?'none':'';

if(fcn)fcn();
}


function dropDown(name,a,b){


var ret='<select class=iText name="'+name+'" id="'+name+'">\n';
for(var i=a;i<=b;i++){
var v=dig2(i);
ret+='<option value="'+v+'">'+v+'</option>';
}
return ret+'</select>';
}

function dropDownArr(name,arr,chg,def,dis,nosel){

chg=chg?' onchange="try{'+chg+'}catch(e){floatError(e)}return false"':'';
var tmp='',len=0;
if(arr)for(var k in arr){
tmp+='<option value="'+k+'" '+(k==def?'SELECTED':'')+'>'+arr[k]+'</option>';
len++;
}

var ret='<select class=iText name="'+name+'" id="'+name+'" '+chg+' '+(dis?'DISABLED':'')+'>\n';
if(!nosel&&len>1)
ret+='<option value="">--SELECT--</option>\n';
return ret+tmp+'</select>';
}

function setDropDown(name,val){

var e=gel(name);
if(!e)
return;
var o=e.options;
if(!o)
return;
for(var i=0;i<o.length;i++)
if(o[i].value==val)
return e.selectedIndex=i;
}

function getCheckedValue(r){

if(!r)return '';
if(!r.length)r=gel(r);

var rLen=r.length;
if(rLen==undefined)
return r.checked?r.value:'';

for(var i=0;i<rLen;i++)
if(r[i].checked)
return r[i].value;

return '';
}

function getSelected(id){

var val=gel(id);
if(val==null||val.options==null)
return '';
if(val.selectedIndex==-1)
return null;
return val.options[val.selectedIndex].value;
}
function setSelected(id,val){

var el=gel(id);
if(el==null||el.options==null)
return;
for(var i=0;i<el.options.length;i++)
if(el.options[i].value==val)
el.selectedIndex=i;
}

function parseNVP(str){

var ret=[],
a=str.split('\n');
for(var i=0;i<a.length;i++){
var p=a[i].split('=');
ret[p[0]]=p[1];
}
return ret;
}

function checkField(f,vals,len){

if(f==null)
return true;

var ret=false,
v=f.value;
if(!v)
return;

if(vals!=null){
n=strIsOnly(v,vals);
if(v!=n){
f.value=n;
try{f.focus();}catch(e){}
ret=true;
}
}

if(v.length>len){
f.value=v.substr(0,len);
try{f.focus();}catch(e){}
ret=true;
}

return ret;
}

function checkFieldHighlight(f){
f.style.background='#ffaaaa';
f.lastVal=f.value;
f.focus();
setTimeout(function(){checkFieldReset(f)},100);
}
cFH=checkFieldHighlight;

function checkFieldReset(f){
if(f.value!=f.lastVal){
f.style.background='';
return f.lastVal=f.value;
}
setTimeout(function(){checkFieldReset(f)},100);
}
function selectFieldText(f,a,b){

if(f.setSelectionRange){
f.focus();
f.setSelectionRange(a,b);
}else if(f.createTextRange){
var r=f.createTextRange();
r.collapse(true);
r.moveEnd('character',b);
r.moveStart('character',a);
r.select();
}
}


function humanTime(t){

t=Math.floor(t);
if(t <60)
return t+'sec';
s=t%60;
return Math.floor(t/60)+':'+Math.floor(s/10)+''+(s%10);
}
function humanNumber(n){
if(n <1000)return n;
if(n <1e6)return Math.floor(n/1000)+','+(n%1000);
if(n <1e9)return Math.floor(n/1000000)+','+(Math.floor(n/1000)%1000)+','+(n%1000);
}
function humanSize(n,bytes){

bytes=bytes?' ('+humanSizeBytes(n)+' Bytes)':'';
n /=1024;
if(n <1024)
return dec2(n*100)+' KB'+bytes;
n /=1024;
if(n <1024)
return dec2(n*100)+' MB'+bytes;
n /=1024
return dec2(n*100)+' GB'+bytes;
}
function humanSizeBytes(n){

var r='';
while(n>1000){
r+=','+(n%1000);
n=Math.floor(n/1000);
}
return n+r;
}

function fixWidth(s){

return '<span style="font:normal 11px Courier New,monospace">'+s+'</span>';
}

function strReplace(str,a,b){


while(str.indexOf(a)!=-1)
str=str.replace(a,b);
return str;
}

function stripHTML(str){

var i;
while((i=str.indexOf('<'))!=-1)
str=str.substring(0,i)+str.substring(str.indexOf('>',i)+1);
return str;
}
function replaceHTML(str){

return strReplace(strReplace(str,'&lt;','<'),'&gt;','>');
}
function safeAmp(str){


return strReplace(strReplace(str,'&','::AMP::'),'::AMP::','&amp;');
}
function safeHTML(str){

return strReplace(strReplace(safeAmp(str),'<','&lt;'),'>','&gt;');
}


function chunk(str,l,s){

var r='';
for(var i=0;i<str.length;i+=l){
if((i%l)==l-1)
r+=s;
r+=str.substring(i,l);
}
return r;
}

function strIsOnly(str,set){

var r='';
for(var i=0;i<str.length;i++){
if(set.indexOf(str.charAt(i))!=-1)
r+=str.charAt(i);
}
return r;
}

function gel(id){
var e,d;
if(e=document.getElementById(id))
return e;
}
function gelt(tag){

return document.getElementsByTagName(tag);
}

function dig2(n){

return Math.floor(n/10)+''+(n%10);
}

function floor2(n){

return Math.floor(n*100)/100;
}
function dec2(n){

n *=1;
var neg=n<0;
if(neg)
n=-n;
n=Math.floor(n);
return(neg?'-':'')+Math.floor(n/100)+'.'+Math.floor((n%100)/10)+''+(n%10);
}
function dec6(n){

n=Math.floor(n);
var ret='';
for(var i=0;i<6;i++){
ret=(n%10)+ret;
n=Math.floor(n/10);
}
return ret;
}

function long2ip(n){

var r='';
if(!n)return r;
for(var i=0;i<4;i++){
r=(n%256)+'.'+r;
n=Math.floor(n/256);
}
return r.substr(0,r.length-1);
}
function ip2long(ip){

if(!ip)return 0;
var A=ip.split('.');
if(A.length!=4)return 0;
return(1*A[0]<<24)+(1*A[1]<<16)+(1*A[2]<<8)+1*A[3];
}


function currencyAcro(c){

var c=SYSINFO.currency;
if(c=='CAD')
c='<acronym title="Canadian Dollar">'+c+'</acronym>';
return c;
}

function buttonS(val,id,frm){
if(!val)
val=wtext('next');


id=id?id:time();
frm=frm?frm:'form1';
return button(val,'try{gel(\''+frm+'\').onsubmit()}catch(e){floatError(e)}',id)+
'<input type="image" width="1" height="1" name="submit" src="i/1.gif" />';
}

function iHide(id,val){

return '<input type=hidden name="'+id+'" id="'+id+'" value="'+val+'" />';
}

var qImgs={
arrow_admin:{x:0,y:153,w:80,h:44},
arrow_bottom:{x:288,y:218,w:236,h:4},
arrow_credit_balance:{x:80,y:153,w:80,h:44},
arrow_profile:{x:160,y:153,w:80,h:44},
arrow_round_corners:{x:708,y:153,w:4,h:44},
arrow_top:{x:0,y:197,w:236,h:4},
border_left:{x:556,y:153,w:14,h:57},
border_left_r:{x:595,y:153},
border_middle:{x:570,y:153,w:10,h:57},
border_middle_r:{x:595,y:181},
border_right:{x:580,y:153,w:14,h:57},
border_right_r:{x:595,y:167},
box_filler:{x:278,y:217},
button_divider:{x:551,y:153,w:2,h:23},
butLeftOff:{x:530,y:153,w:10,h:21},
butLeftOn:{x:530,y:174,w:10,h:21},
butFillOff:{x:540,y:153},
butFillOn:{x:540,y:174},
butRightOff:{x:541,y:153,w:10,h:12},
butRightOn:{x:541,y:174,w:10,h:12},
ctlMoveOff:{x:240,y:153,w:51,h:23},
ctlMoveOn:{x:240,y:176,w:51,h:23},
ctlNewfOff:{x:291,y:153,w:85,h:23},
ctlNewfOn:{x:291,y:176,w:85,h:23},
ctlNewpOff:{x:376,y:153,w:89,h:23},
ctlNewpOn:{x:376,y:176,w:89,h:23},
ctlRenaOff:{x:465,y:153,w:65,h:23},
ctlRenaOn:{x:465,y:176,w:65,h:23},
buyCredOff:{x:611,y:177,w:97,h:21},
buyCredOn:{x:611,y:198,w:97,h:21},
corner_bottom_left:{x:0,y:201,w:139,h:18},
corner_bottom_right:{x:139,y:201,w:139,h:18},
corner_top_left:{x:278,y:199,w:139,h:17},
corner_top_leftbg:{x:278,y:216},
corner_top_right:{x:417,y:199,w:139,h:17},
corner_top_rightbg:{x:268,y:200},
filler_bottom:{x:553,y:153},
filler_top:{x:594,y:153},
icon_calendar:{x:574,y:210,w:14,h:14},
icon_search:{x:556,y:210,w:18,h:18},
receiptLogo:{x:712,y:153,w:290,h:70},
refillOff:{x:591,y:211,w:24,h:24},
refillOn:{x:601,y:211,w:24,h:24},
ctlRefrOff:{x:609,y:153,w:24,h:24},
ctlRefrOn:{x:633,y:153,w:24,h:24},
rounded_corners_bottom:{x:0,y:127,w:1002,h:26},
rounded_corners_top:{x:0,y:110,w:1002,h:17},
top_logo_nav:{x:0,y:0,w:1002,h:110},
minus:{x:533,y:216,w:11,h:11},
plus:{x:544,y:216,w:11,h:11},
down:{x:595,y:191,w:12,h:10},
up:{x:595,y:201,w:12,h:10},
checkBlue:{x:94,y:223,w:16,h:16},
checkBlue2:{x:77,y:223,w:16,h:16},
folder:{x:0,y:223,w:16,h:16},
folderAdd:{x:18,y:223,w:16,h:16},
folderGo:{x:56,y:223,w:16,h:16},
folderEdit:{x:38,y:223,w:16,h:16},
'':{x:-100,y:-100}
};
function qImgSet(id,name){
var I=qImgs[name],el;
if(!I)return alert('Could not find imginfo='+name);
if(id.id)el=id;else
if(!(el=gel(id)))return alert('Could not find element id='+id);
debug('qImgSet('+id+','+name+')');
if(name=='')return el.style.background='transparent';
el.style.background='transparent url(i/wxpall.png) no-repeat '+(-I.x)+'px '+(-I.y)+'px';
}
function qImg(name,id,cls,txt,clk){
var I=qImgs[name],bg;
if(!I)return alert('Could not find imginfo='+name);
if(!clk||clk=='')clkF=function(s){return s;}
else clkF=function(s){return '<a href="'+clk+'" onclick="'+clk+'">'+s+'</a>'; }

return '<table class=tight><tr><td style="background:#ffffff url(i/wxpall.png) no-repeat '+(-I.x)+'px '+(-I.y)+'px">'+
clkF('<img src=i/1.gif width='+I.w+' height='+I.h+' />')+
'</td></tr></table>';
}
function qImgTd(name,id,cls,txt,clk){
var I=qImgs[name],bg,sty='';
if(!id||id=='')id='';
else id='id="'+id+'"';
if(!txt||txt=='')txt='';
if(!cls||cls=='')cls='';
else if(cls.indexOf('style=')!=-1){sty=strReplace(cls.substr(6),'~',':')+';'; cls=''; }
else cls='class="'+cls+'"';
if(!clk||clk=='')clkF=function(s){return s;}
else clkF=function(s){return '<a href="'+clk+'" onclick="'+clk+'">'+s+'</a>'; }

if(!I)return alert('Could not find imginfo='+name);

return '<td '+id+' '+cls+' style="'+sty+'background:#ffffff url(i/wxpall.png) no-repeat '+(-I.x)+'px '+(-I.y)+'px">'+
clkF((I.w?'<img src=i/1.gif width='+I.w+' height='+I.h+' />':'')+txt)+
'</td>';
}

var iCals=null;
function iCal(id,v,hideDate,size,txt,rstclk,chgclk){

if(iCals==null){
iCals=[];
iCalWatcher();
}

if(!rstclk)rstclk='';
if(!txt)txt='';
else txt='&nbsp;'+txt;

if(!v)v='';
if(v=='TODAY')v=iCalToday();
if(v=='TOMORROW')v=iCalTomorrow();
if(v=='YEARSTART')v=iCalYearStart();
if(v=='MONTHSTART')v=iCalMonthStart();
if(v=='YEAREND')v=iCalYearEnd();
if(v=='MONTHEND')v=iCalMonthEnd();

if(!size)size='style="width:67px"';
else{
size+='';
if(size.indexOf('%')!=-1||size.indexOf('px')!=-1)
size='style="width:'+size+'"';
else
size='size='+size;
}

var rv=v,
cal=new CalendarPopup('floaterCal');
cal.setMonthNames('Jan','Feb','Mär','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
if(iCals[id]&&iCals[id].val)
v=iCals[id].val;

cal.addDisabledDates(strReplace(iCalTomorrow(),'/','-'),null);
iCals[id]={cal:cal,val:v,chgclk:chgclk};

var clk='iCals[\'{ID}\'].cal.select(gel(\'{ID}\'),\'{ID}link\',\'yyyy/MM/dd\');return false';
var clk='iCals[\'{ID}\'].cal.select(gel(\'{ID}\'),\'{ID}link\',\'MMM dd yyyy\');return false';
return parseTmpl('<table style="border-collapse:collapse;padding:0px"><tr>'+
'<td style="padding:0px"><input class=caliText type="{TYPE}" name="{ID}" id="{ID}" value="{VAL}"{SIZE}onchange="iCals[\'{ID}\'].val=value;{CHGCLK}" /></td>'+
qImgTd('icon_calendar',0,'style=padding~0px',0,clk)+
'<td style="padding:0px"><a href="#" name="{ID}link" id="{ID}link" onclick="{CLK}">{TXT}</a></td>'+
'<td style="padding:0px">[{RESET}]</td>'+
'</tr></table>',
{CLK:clk,RESET:iLink(' iCalSet(\'{ID}\',\'{RVAL}\');{RSTCLK}','Reset'),
TYPE:hideDate?'hidden':'text',ID:id,VAL:v,RVAL:rv,SIZE:size,TXT:txt,RSTCLK:rstclk,CHGCLK:chgclk});
}
function iCalSet(id,v){
if(!iCals[id])
return 0;
return gel(id).value=iCals[id].val=iCals[id].lastval=v;
}
function iCalWatcher(){

for(var k in iCals){
var C=iCals[k],
v=gel(k);
if(v)
if((v=v.value)!=C.val)
C.val=v;


if(!(v=C.lastval))
v=C.val;
if(!gel(k))continue;
if(v!=gel(k).value){
debug('iCalWatcher id:'+k+' value:'+gel(k).value+' v:'+v+' C.val:'+C.val+' last:'+C.lastval);
gel(k).onchange();
}
C.lastval=gel(k).value;
}
setTimeout(iCalWatcher,500);
}
function iCalDate(off){
if(!off)off=0;
return new Date(gmt2localval(gmtime()+off)*1000);
}
function iCalToday(){
var d=iCalDate();

return MONTH_NAMES[12+d.getMonth()]+' '+dig2(d.getDate())+' '+d.getFullYear();
}
function iCalTomorrow(){
var d=iCalDate(60*60*24);

return MONTH_NAMES[12+d.getMonth()]+' '+dig2(d.getDate())+' '+d.getFullYear();
}
function iCalYearStart(){
var d=iCalDate();

return 'Jan 01 '+d.getFullYear();
}
function iCalYearEnd(){
var d=iCalDate();

return 'Dec 31 '+d.getFullYear();
}
function iCalMonthStart(){
var d=iCalDate();

return MONTH_NAMES[12+d.getMonth()]+' 01 '+d.getFullYear();
}
function iCalMonthEnd(){
var d=iCalDate();
m=d.getMonth()+1,
dy=31;
if(m==2)
dy=28;
if(m==4||m==6||m==9||m==11)
dy=30;

return MONTH_NAMES[12+m-1]+' '+dy+' '+d.getFullYear();
}
function iCalTime(id,def){
var D=new Date(getVal(id,def));
debug('iCalTime('+id+','+def+')del='+currentTimeDelta+' ret='+(D.getTime()/1000-currentTimeDelta));
return D.getTime()/1000-currentTimeDelta;
}

var buttonN=0;
function button(val,clk,id,textcol){

buttonN++;
textcol=(textcol==null)?'':textcol;
id=(id==null||id=='')?('button'+buttonN):id;
clk=(clk==null||clk=='')?'':' onclick="try{'+clk+'}catch(e){floatError(e)}"';

return wtext('button.html',{ID:id,CLK:clk,VAL:val});
}
function buttonOver(B){
var T=gel(B.id+'_ctr');
B.onmouseout=function(){T.style.textDecoration='none'; }
T.style.textDecoration='underline';
}
function buttonCancel(){
return button(wtext('cancel'),'fC()');
}

function linkOver(o){
o.style.textDecoration='none';
o.onmouseout=function(){linkOut(o);};
}
function linkOut(o){
o.style.textDecoration='underline';
}

function disableButton(b){

var B=gel(b);
if(!B)
return;
if(B.onclick&&B.onclick!=''){
B.oldonclick=B.onclick;
B.oldonmouseover=B.onmouseover;
B.oldonmouseout=B.onmouseout;
B.onclick='';
B.onmouseover='';
B.onmouseout='';
}

B.style.cursor='default';
qImgSet(b+'_lft','butLeftOff');
qImgSet(b+'_rgt','butRightOff');
var I=gel(b+'_ctr').style;I.background='#fff url(i/wxpbg.png) no-repeat 0px -21px';

}
function enableButton(b){

var B=gel(b);
if(!B)
return;
if(!B.onclick||B.onclick==''){
B.onclick=B.oldonclick;
B.onmouseover=B.oldonmouseover;
B.onmouseout=B.oldonmouseout;
}

B.style.cursor='pointer';
qImgSet(b+'_lft','butLeftOn');
qImgSet(b+'_rgt','butRightOn');
var I=gel(b+'_ctr').style;I.background='#fff url(i/wxpbg.png) no-repeat 0px 0px';

}

function setCookie(pair,expdays){

var exp='';
if(expdays){
var ex=new Date();
ex.setDate(ex.getDate()+expdays);
exp=';expires='+ex.toGMTString();
}

document.cookie=pair+';path='+getCookiePath()+exp+';'+(forceSSL?'secure':'');
}
function getCookiePath(){
debug('getCookiePath()url='+URL+'  ret=/'+URL.split('/')[3]+'/');
var dir=URL.split('/')[3];
if(dir.indexOf('?')==-1)
return '/'+URL.split('/')[3]+'/';
return '/';
}

function getCookie(key){
if(!getCookie.once){
getCookie.once=1;
debug('cookies=\n'+print_r(strReplace(document.cookie,'; ',';').split(';')));
}


var kv,
arr=strReplace(document.cookie,'; ',';').split(';');
for(var i=0;i<arr.length;i++){
kv=[0,0];
kv=arr[i].split('=');
if(kv[0]==key)
return kv[1]?kv[1]:'';
}
return '';
}

function genPassword(id){

var let='0123456789ABCDEFGHIJKLMN'+'PQRSTU'+'WXYZ',
t='genPassword.',
pswd='';
for(var i=0;i<8;i++){
if(i&&(i%4)==0)
pswd+='-';
pswd+=let.charAt(Math.floor(Math.random()*let.length));
}

floatAsk(wtext(t+'title'),
wtext(t+'body',{PSWD:pswd}),
[button(wtext('cancel'),'fH(2);blanketScreen()'),
button(wtext('next'),'genPasswordDone(\''+id+'\',\''+pswd+'\')')],
2);
}

function genPasswordDone(id,pswd){

gel(id).value=pswd;
fH(2);
blanketScreen();
}












function wtext(k,arr){

if(getCookie('wxplang')=='')
LANG='en-CA';

if(!webtext||!webtext[LANG])
return '';

var r=webtext[LANG][k];
if(r==null)
return 'Error: website content missing language='+LANG+' tag='+k;

return arr?parseTmpl(r,arr):r;
}

function base(d){


return BASEURL+APP;//+'?'+d;
}

function loggedIn(){

var a=wxpauth;
if(!a||a=='')
a=getCookie('wxpauth');
if(a&&a!=''){
wxpauth=a;
return !inactiveLogout();
}
return false;
}
function inactiveLogout(){
return wxpauth!=''&&inactiveFor()>60*60;
}
function inactiveFor(){

return gmtime()-tzOffset()-getAuthTime();
}
function otherLogin(){

var cook=getCookie('wxpauth');
if(!cook)
return true;
if(wxpemail&&getCookie('wxpsuper')==''&&wxpemail!=unescape(getCookie('wxpemail')).toLowerCase()){
alert('2nd login msg\n'+
wxpemail+'\n'+
unescape(getCookie('wxpemail')).toLowerCase());
return true;
}
if(getUserId(wxpauth)!=getUserId(cook)){
alert('2nd login msg,2\n'+
getUserId(wxpauth)+'\n'+
getUserId(cook));
return true;
}
return false;
}


var b64=null;
function b64dec(s){

if(!s||s=='')
return '';
var i,v,k=0,j=0,r='';

if(b64==null){
b64=[];
for(i=0;i<256;i++)b64[i]=-1;
for(i=0;i<26;i++){
b64[0x41+i]=i;
b64[0x61+i]=i+26;
if(i<10)
b64[0x30+i]=i+52;
}
b64[0x2d]=b64[0x2b]=62;
b64[0x5f]=b64[0x2f]=63;
}

for(i=0;i<s.length;i++){
v=b64[s.charCodeAt(i)];
if(v==-1)
continue;
j<<=6;
k+=6;
j|=v;
if(k>=8){
k-=8;
r+=String.fromCharCode((j>>k)&0xff);
}
}

return r;
}


function quicksort(a,cmp){

quicksort_(a,cmp,0,a.length-1);
}
function quicksort_(a,cmp,s,e){

if(e <=s)
return;
var p=a[s],
i=s,
j=e+1;

for(;;){
while(++i <e&&cmp(a[i],p)<0);
while(--j>s&&cmp(a[j],p)>0);
if(j <=i)
break;

var t=a[i];
a[i]=a[j];
a[j]=t;
}

a[s]=a[j];
a[j]=p;

quicksort_(a,cmp,s,j-1);
quicksort_(a,cmp,j+1,e);
}





function utime(){

return(new Date()).getTime();
}
function time(){

return Math.floor(utime()/1000);
}
function gmtime(){

return time()-currentTimeDelta;
}

function timeAndAgo(t){

return gmt2local(t)+'<br/>'+timeAgo(t);
}

function tzOffset(){

return(new Date()).getTimezoneOffset()*60;
}

function gmt2localval(gmtval){

return 1*gmtval+currentTimeDelta+tzOffset();
}
function gmt2local(t){

return local(gmt2localval(t));
}
function gmt2localshort(t){

return localshort(gmt2localval(t));
}
function gmt2local2line(t){

var t=gmt2local(t);
return t.substr(0,11)+'<br/>'+t.substr(12);
}

function timeAgo(then){

var D=gmtime()-tzOffset()-then,
w='ago';
if(D <0){
D=-D;
w='from now';
}

var d=Math.floor(D/24/60/60),
h=Math.floor(D/60/60)%24,
m=Math.floor(D/60)%60,
s=D%60,
r='';
if(d!=0)
r+=d+' days ';
r+=dig2(h)+':'+dig2(m)+':'+dig2(s);

return r+' '+w;
}

function localshort(t){

if(t==null||t==0)
return '<i>'+wtext('time.empty')+'</i>';

var d=new Date(gmt(t-currentTimeDelta)),
n=new Date(),
Y=new Date(n.getFullYear()+'/'+dig2(n.getMonth()+1)+'/'+dig2(n.getDate())),
del=d.getTime()-Y.getTime();

return MONTH_NAMES[12+d.getMonth()]+' '+dig2(d.getDate())+' '+d.getFullYear();
if(del <0||del>24*60*60*1000){
return d.getFullYear()+'/'+dig2(d.getMonth()+1)+'/'+dig2(d.getDate());
}else{
return dig2(d.getHours())+':'+dig2(d.getMinutes())+':'+dig2(d.getSeconds());
}
}

function local(t){

if(t==null||t <=50000)
return '<i>'+wtext('time.empty')+'</i>';

var d=new Date(gmt(t-currentTimeDelta)),
ap='AM',
hr=d.getHours();
if(hr>=12){
hr-=12;
ap='PM';
}
if(hr==0)hr=12;


return MONTH_NAMES[12+d.getMonth()]+' '+dig2(d.getDate())+' '+d.getFullYear()+' '+
dig2(hr)+':'+dig2(d.getMinutes())+':'+dig2(d.getSeconds())+' '+ap;
}

function gmt(t){

if(t==null||t==0)
return '<i>'+wtext('time.empty')+'</i>';

var d=new Date(t*1000);
return d.getFullYear()+'/'+dig2(d.getMonth()+1)+'/'+dig2(d.getDate())+' '+
dig2(d.getHours())+':'+dig2(d.getMinutes())+':'+dig2(d.getSeconds())+' UTC';
}
function gmt2line(t){

return gmt(t).replace(' ','<br/>');
}

function utc(d){

if(d.indexOf('20')!=0)
d='20'+d;
var s=d.substr(0,4)+'/'+d.substr(4,2)+'/'+d.substr(6,2)+' '+
d.substr(8,2)+':'+d.substr(10,2)+':'+d.substr(12,2)+' UTC',
v=Date.parse(s);
return v/1000;
}





function parseEmail(str){
var A=str.split('|');
return{addr:A[0],disp:b64dec(A[1])};
}
function showEmail(e){
return '"'+e.disp+'" &lt;'+e.addr+'&gt;';
}






















function parseResponse(resp){

var kvl,r=[],l=resp.split('\n');

for(var i=0;i<l.length;i++){
if(l[i].length==0||l[i].indexOf('//')==0)
continue;

var kv=l[i].split('=');
if(kv.length!=2){
debug('parseResponse skiping line i='+i);
continue;
}
if(kv[0]=='')
kv[0]=kvl.replace('::','');

var a=kv[1].split(','),
rv=[];
for(var j=0;j<a.length;j++){

var idx;
if((idx=a[j].indexOf(':'))!=-1){
rv[a[j].substring(0,idx)]=a[j].substring(idx+1);
}
else if(r['::'+kv[0]]){
var k=r['::'+kv[0]][0][j];
if(k)
rv[k]=a[j];
}
else{
rv[rv.length]=a[j];
}
}

var k=kvl=kv[0];
if(!r[k])
r[k]=[];
r[k][r[k].length]=rv;
}

return r;
}

function print_r(o,s){

if(!s)
s='';
var ret='';
for(var k in o){
ret+=s+k+'=';
if(o[k])
ret+=(o[k].constructor==Array?('Array(\n'+print_r(o[k],s+' ')+')'):o[k]);
else
ret+='null';
ret+='\n';
}
return ret;
}

function parseqimg(str){

str=''+str;
var idx=str.indexOf('pimg(');
if(idx==-1)
return;
var n=str.substring(idx),
end=n.indexOf(')'),
code=str.substring(idx+5,idx+end+1),
r='';
eval('var r=qimg('+code+';');
return strReplace(str,'<script type="text/javascript">pimg('+code+';</script>',r);
}

function justErrorResp(r){

var ret='',arr=r.split('\n');
for(var i=0;i<arr.length;i++)
if(arr[i].indexOf('Error:')!=-1)
ret+=arr[i]+'\n';
return ret;
}




function parseCounter(t){
var idx,n=0;
while((idx=t.indexOf('{**N:2}'))>-1)
t=t.substring(0,idx)+(n=(n+1)%2)+t.substring(idx+7);



return t;
}
function loadTmpls(R){

gel('debug').innerHTML+='R='+R+'<hr/>\n';
if(!R){
var TDs=gelt('td'),
SPANs=gelt('span');
loadTmpls(TDs);
loadTmpls(SPANs);


var el=gelt('input');
for(var i=0;i<el.length;i++){
if(el[i].className=='iSearch'){
el[i].onfocus();
el[i].onblur();
}
}
return setTimeout(loadClocks,1000);
}

for(var i=0;i<R.length;i++){
if(R[i].className==null||R[i].className=='')continue;
var h=replaceMap(R[i].className.split(':'));
if(h)R[i].innerHTML=h;
}


gel('debug').innerHTML='';
}

function parseTmpl(t,pairs){

pairs.RND=Math.floor(1e7*Math.random());
for(var k in pairs)
t=strReplace(t,'{'+k+'}',pairs[k]);

var start;
while((start=t.indexOf('{button'))!=-1||

(start=t.indexOf('{submit'))!=-1||
(start=t.indexOf('{iForm'))!=-1||
(start=t.indexOf('{iHide'))!=-1||
(start=t.indexOf('{iText'))!=-1||
(start=t.indexOf('{iPswd'))!=-1||
(start=t.indexOf('{iCheck'))!=-1||
(start=t.indexOf('{iLink'))!=-1||
(start=t.indexOf('{imgLink'))!=-1||
(start=t.indexOf('{iCal'))!=-1||
(start=t.indexOf('{floatMenu'))!=-1||
(start=t.indexOf('{dropDown'))!=-1||
(start=t.indexOf('{qImg'))!=-1||
(start=t.indexOf('{qImgTd'))!=-1||
(start=t.indexOf('{*'))!=-1){
var end=t.indexOf('}',start),
I=t.substring(start+1,end).split(':'),
b='';

b=replaceMap(I);
t=t.substring(0,start)+b+t.substring(end+1);
}

return t;
}
function replaceMap(I){
var b;

if(I[0]=='*SUBMITIMG*')		b=subimg();
else if(I[0]=='*S')			b=S(I[1]);
else if(I[0]=='*SV')			b=VS(I[1]);
else if(I[0]=='button')		b=button(I[1],I[2],I[3],I[4]);
else if(I[0]=='buttonG')	b=buttonG(I[1],I[2],I[3]);
else if(I[0]=='submit')		b=buttonS(I[1],I[2],I[3]);
else if(I[0]=='iForm')		b=iForm(I[1],I[2],I[3]);
else if(I[0]=='iText')		b=iText(I[1],I[2],I[3]);
else if(I[0]=='iHide')		b=iHide(I[1],I[2]);
else if(I[0]=='iPswd')		b=iPswd(I[1],I[2],I[3]);
else if(I[0]=='iCheck')		b=iCheck(I[1],I[2],I[3],I[4]);
else if(I[0]=='iLink')		b=iLink(I[1],I[2],I[3],I[4]);
else if(I[0]=='drawClock')	b=drawClock(I[1]);
else if(I[0]=='imgLink')	b=imgLink(I[1],I[2],I[3],I[4],I[5],I[6],I[7]);
else if(I[0]=='imgLinkPad')b=imgLinkPad(I[1],I[2],I[3],I[4],I[5],I[6],I[7]);
else if(I[0]=='iCal')		b=iCal(I[1],I[2],I[3],I[4],I[5],I[6],I[7]);
else if(I[0]=='qImg')		b=qImg(I[1],I[2],I[3],I[4],I[5]);
else if(I[0]=='qImgTd')		b=qImgTd(I[1],I[2],I[3],I[4],I[5]);
else if(I[0]=='dropDown'){
var arr=I[3].split(','),assoc={};
if(I[3]=='*COUNTRIES')assoc=countries;
else if(I[3]=='*GROUPS'){
var G=profile.groups;
assoc['0']='Personal Credits';
if(G)for(var i=0;i<G.length;i++)
assoc[G[i].id]=G[i].name;
}
else if(I[3]=='*CREDITS'){
var SCH=SYSINFO['credit.schedule'];
for(var k in SCH)
if(k.indexOf('@')==-1)
assoc[k]=k+' credits for $'+dec2(SCH[k].subtotal*100);
}
else for(var i=0;i<arr.length;i++){
var kv=arr[i].split('=');
if(kv.length==1)
assoc[arr[i]]=arr[i];
else
assoc[kv[0]]=kv[1];
}
b=dropDownArr(I[1],assoc,I[2],I[4],0,1);
}
else if(I[0]=='floatMenu'){
b=t.substring(t.indexOf(':',t.indexOf(I[1],start))+1,end);
b=floatMenu(I[1],strReplace(b,'\n','').split('|'));
}
else{
return null;
}

return b;
}
function subimg(){

return '<input name="submit" type="image" src="i/1.gif" height="1" width="1" />';
}


ckajax=new Object();

ckajax.times=[];

ckajax.cacheTime=60*1000;
ckajax.cache=[];
ckajax.clearCache=function(){
ckajax.cache=[];
};

ckajax.getCached=function ckajax_getCached(url,postdata,complete,user,pswd,headers){
var key=url+'?'+postdata,
idx=key.indexOf('wxpauth');
if(idx!=-1)
key=key.substring(0,idx);
var c=ckajax.cache[key];
if(c!=null&&(new Date()).getTime()<(c[0]+ckajax.cacheTime)){
if(complete==null)
return c[1];
else
return complete(200,'OK',c[1]);
}
return ckajax.getText(url,postdata,complete,user,pswd,headers);
};

ckajax.ieCacheCheck=function ckajax_ieCacheCheck(xmlreq,url,postdata){
if(!xmlreq.getResponseHeader('Date')){
var mod=xmlreq.getResponseHeader('Last-Modified');
mod=mod?mod:new Date(0);

var t=ckajax.getXmlReq();
t.open((postdata!=null?'POST':'GET'),url,false);
t.setRequestHeader('If-Modified-Since',mod);
t.send('');
if(t.status==304)
return xmlreq;
return t;
}

return xmlreq;
};

ckajax.getXmlReq=function ckajax_getXmlReq(){
if(window.XMLHttpRequest){
try{
return new XMLHttpRequest();
}catch(e){
return 'Error: Could not open XMLHttpRequest;old browser?';
}
}
else if(window.ActiveXObject){
try{
return new ActiveXObject('Msxml2.XMLHTTP');
}catch(e){
try{
return new ActiveXObject('Microsoft.XMLHTTP');
}catch(e){
return 'Error: Could not open ActiveXObject;old browser?';
}
}
}

return 'Error: Cannot load any XMLHttpRequest objects;really old browser?';
};












ckajax.getText=function ckajax_getText(url,postdata,complete,user,pswd,headers){

var xmlreq,
caller=arguments.callee.caller,
tran=ckajax.times.length,
start=(new Date()).getTime(),
key=url+'?'+postdata,
idx=key.indexOf('wxpauth');
if(idx!=-1)
key=key.substring(0,idx);

if(url.indexOf('://')!=-1&&url.indexOf('://'+document.location.host+'/')==-1)
return 'Error: Script host must match page host.';

xmlreq=ckajax.getXmlReq();

if(complete){
xmlreq.onreadystatechange=function ckajax_getText_stateChange(){
if(xmlreq.readyState==4){
var now=(new Date()).getTime();
try{
var t=xmlreq.status;
}catch(e){
return complete(-1,'unk','Could not contact server,try again later');
}

try{
xmlreq=ckajax.ieCacheCheck(xmlreq,url,postdata);
}catch(e){
complete (-1,'Communication Problem','Error: Communication error,&nbsp;please check internet connection and try again.');
}

if(xmlreq.status==200||xmlreq.status==304){
if(xmlreq.responseText.indexOf('Error:')!=0)
try{ckajax.cache[key]=[now,xmlreq.responseText];}catch(e){debug(e.message+'\n'+stackTrace())}
}
if(xmlreq.responseText.indexOf('Error: System is offline')!=-1)
return document.location.href='?offline';

ckajax.times[tran]=now-start;
if(typeof debug=='function')debug('ckajax.times['+tran+']['+url+']='+ckajax.times[tran]+' resplen='+xmlreq.responseText.length);

try{
complete(xmlreq.status,xmlreq.statusText,xmlreq.responseText);
}catch(e){floatError(e,null,caller);}
}
};
}

try{
xmlreq.open((postdata!=null?'POST':'GET'),url,complete!=null,user,pswd);

if(postdata!=null)
xmlreq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

if(headers!=null){
var hdr=headers.split('\n');
for(var i=0;i<hdr.length;i++){
if(hdr[i].length==0)continue;
var nv=hdr[i].split(': ');
xmlreq.setRequestHeader(nv[0],nv[1]);
}
}

xmlreq.send(postdata);
}catch(e){
return 'Error: Communication error,&nbsp;Please check internet connection and try again.';
}

if(complete!=null)
return 'OK';

try{

xmlreq=ckajax.ieCacheCheck(xmlreq,url,postdata);
}catch(e){
return 'Error: Communication Error,&nbsp;Please check internet connection and try again.';
}

if(xmlreq.status!=200)
return 'Error: '+xmlreq.status+' status: '+xmlreq.statusText;

if(xmlreq.responseText.indexOf('Error: System is offline')!=-1)
return document.location.href='?offline';

ckajax.times[tran]=(new Date()).getTime()-start;

if(xmlreq.responseText.indexOf('Error:')!=0)
ckajax.cache[key]=xmlreq.responseText;

return xmlreq.responseText;
};

ckajax.importJS_list=[];
ckajax.importJS=function ckajax_importJS(url,fnc){
if(ckajax.importJS_list[url]){
if(typeof debug=='function')debug('script url "'+url+'" already loaded');
return fnc!=null?setTimeout(fnc,100):null;
}
var s=document.createElement('script');
s.type='text/javascript';
s.src=url;
document.getElementsByTagName('head')[0].appendChild(s);

if(typeof debug=='function')debug('script url "'+url+'" fetched');

ckajax.importJS_list[url]=true;
if(fnc!=null)
setTimeout(fnc,100);
};






function wxpLoading(F){

var html=wtext('loading.fill'),
T=gel('treeDIV'),
E=gel('emailDIV');
if(F)
return gel(F).innerHTML=html;

if(!T)return;

/*
debug('navigator.userAgent='+navigator.userAgent);
if(navigator.userAgent.indexOf('Chrome')!=-1){
T.style.overflowY=
E.style.overflowY='auto';
}else{
T.style.overflowY=
E.style.overflowY='scroll';
}
//*/
T.innerHTML=
E.innerHTML=html;
}


function wxpStart(){
preloadImages();
loadTmpls(0);

var idx=URL.indexOf('?');

if(URL.indexOf('?signup')!=-1)
return oncePreloadImageDone(showSignup);

if(URL.indexOf('?reg')==-1&&URL.indexOf('?login')==-1){
var N=gel('navLogout');
if(N)N.innerHTML=inactiveLogout()?'LOGIN':'DASHBOARD';
return;
}

wxpLoading();
if(forceSSL&&URL.indexOf('https://')!=0){
document.location.href=URL.replace('http://','https://');
return;
}

wxpauth=getCookie('wxpauth');
if(!wxpauth||wxpauth=='')
return showLogin();
if(URL.indexOf('?reg')==-1)
return gotoPage('reg');

showMain();

//resizeDIVs();
floatTrimTextUpdate();
}

var resizeDIVs_last = 0;
function resizeDIVs() {
  var E = gel('emailDIV'),
    T = gel('treeDIV'),
    C = gel('wxpContainer'),
    W = getWindowSize(),
    L = 100; // limit number of loops

//var T = gel('treeDIV'), E = gel('emailDIV'),T0 = gel('treeDIV0'); if(!T0)T0=T;  alert('E='+ E.style.width +','+ E.style.height +' T='+ T.style.width +','+ T.style.height +' T0='+ T0.style.width +','+ T0.style.height +'\n'+ 'E='+ E.offsetWidth +','+ E.offsetHeight +' T='+ T.offsetWidth +','+ T.offsetHeight +' T0='+ T0.offsetWidth +','+ T0.offsetHeight);

  if (T && W.wy != resizeDIVs_last) {
    var pre = C.clientHeight;
//try{
    do {
      if (E.offsetHeight == 0)  break;
      E.style.height = /*T.style.height =*/ (parseInt(E.style.height)+10)+'px';
      if (--L <= 0) break;
    } while (C.clientHeight <= W.wy || C.clientHeight == pre);
    do {
      if (E.offsetHeight == 0)  break;
      var v = (parseInt(E.style.height)-16)+'px';
//      T.style.height =
      E.style.height = v;
//      E.style.height = T.style.height = (parseInt(E.style.height)-1)+'px';
      if (--L <= 0) break;
    } while (C.clientHeight > W.wy  &&  E.style.height > 100);
//}catch(e){ alert(e.message +'\n'+ print_r(e)); }
    resizeDIVs_last = W.wy;
  }

  setTimeout(resizeDIVs, 1000);
}
/*
var resizeDIVs_last=0;
function resizeDIVs(){
var E=gel('emailDIV'),
T=gel('treeDIV'),
C=gel('wxpContainer'),
W=getWindowSize(),
L=100;

if(T&&W.wy!=resizeDIVs_last){
E.style.height=T.style.height='128px';
var pre=C.clientHeight;
var x='\n';

do{
if(E.offsetHeight==0)break;
x+='E='+pre+'/'+E.offsetWidth+','+E.offsetHeight+' ('+E.style.width+','+E.style.height+')C='+C.clientWidth+','+C.clientHeight+' W='+W.wx+','+W.wy+'  new='+(parseInt(E.style.height)+1)+'<br/>\n';
E.style.height=T.style.height=(parseInt(E.style.height)+10)+'px';
if(--L <=0)break;
}while(C.clientHeight <=W.wy||C.clientHeight==pre);
x+='C.height='+C.clientHeight+' vs '+W.wy+'<br/>\n';
do{
if(E.offsetHeight==0)break;
x+='e='+pre+'/'+E.offsetWidth+','+E.offsetHeight+' ('+E.style.width+','+E.style.height+')C='+C.clientWidth+','+C.clientHeight+' W='+W.wx+','+W.wy+'  new='+(parseInt(E.style.height)-1)+'<br/>\n';
var v=(parseInt(E.style.height)-1)+'px';
E.style.height=v;
T.style.height=v;

if(--L <=0)break;
}while(C.clientHeight>W.wy&&E.style.height>100);

debug('resizeDIVs\n'+x);
resizeDIVs_last=W.wy;
}

setTimeout(resizeDIVs,1000);
}
//*/

function loadClocks(){

try{
CoolClock.findAndCreateClocks();
}catch(e){
debug('loadClocks()e='+e.message);
setTimeout(loadClocks,1000);
}
}


function wxpSignup(){

showSignup();
}



var dragObject=null,
mouseOffset=null;
function getPosition(e){

var l=0,
t=0;

while(e.offsetParent){
l+=e.offsetLeft;
t+=e.offsetTop;
e=e.offsetParent;
}

l+=e.offsetLeft;
t+=e.offsetTop;

return{x:l,y:t};
}

function getMouseOffset(t,ev){

ev=ev||window.event;
var doc=getPosition(t),
mou=mouseCoords(ev);
return{
x:mousePos.x-docPos.x,
y:mousePos.y-docPos.y
};
}

function mouseMove(ev){

ev=ev||window.event;
var mou=mouseCoords(ev);
if(dragObject){
var o=dragObject;
o.style.position='absolute';
o.style.top=mou.y-mouseOffset.y;
o.style.left=mou.x-mouseOffset.y;
return false;
}
}

function mouseUp(){

dragObject=null;
}

function makeDraggable(id){

var e=gel(id);
if(!e)return;
e.mousedown=function(ev){
dragObject=this;
mouseOffset=getMouseOffset(this,ev);
return false;
}
}
document.mousemove=mouseMove;
document.mouseup=mouseUp;

function checkAdminSearch(){

if(!gel('adminTable'))
return;

var e,ipvals='0123456789.';
if(e=gel('user_ip'))
checkField(e,ipvals,4*3+3);

if(e=gel('user_cardnum4'))
checkField(e,nums,4);

setTimeout(checkAdminSearch,500);
}


var sysadmin={timeout:0,searchView:'',groupid:-1,firmid:-1};

function showAdmin(){

sysadmin.firmid=sysadmin.groupid=-1;
var html=
'<br/>'+
'<span id=adminTitle style="font:bold normal 16px Lucida,sans-serif">Loading</span><br/><br/>\n'+
'<table style="background-color:#ffffff;width:1002px;height:100%;"><tr><td align=left valign=top>\n'+
'['+iLink('showRegistry(1)','Back to Registry')+'&nbsp;'+
'| '+iLink('createUser()','Create User')+'&nbsp;'+
'| '+iLink('showAdminSearch(\'users\')','User List')+'&nbsp;'+
'| '+iLink('showAdminSearch(\'logins\')','Login Log')+'&nbsp;'+
'| '+iLink('showAdminSearch(\'files\')','Postmarked Email')+'&nbsp;'+
'| <a target=_webstats href="https://www.trustifi.com/admin-stats/awstats.pl">Web Stats</a>&nbsp;'+
'| '+iLink('showAdminSearch(\'errors\')','Error Log')+'&nbsp;'+
'| '+iLink('showAdminSearch(\'errors_user\')','User Error Log')+'&nbsp;'+
'| '+iLink('showAdminSearch(\'errors_email\')','Email Error Log')+'&nbsp;'+
'| '+iLink('showAdminSearch(\'tracking\')','Tracking Log')+'&nbsp;]<br/>\n'+
'['+iLink('showAdminSearch(\'purchases\')','Purchase Log')+'&nbsp;'+
'| '+iLink('showEndOfDay()','End Of Day Review')+'&nbsp;]<br/><br/>\n';
if(URL.indexOf('-staging')!=-1||URL.indexOf('-testing')!=-1)
html+='['+iLink('editContent()','Edit Content')+']<br/><br/>\n';
html+=
'<span style="font:normal 12px Lucida,sans-serif" id=summary></span>\n'+
iLink('ghostUser(-1)','','ghostDisable')+'<br/><br/>\n'+
'<span id=adminTable style="display:none"><input type=hidden name=searchType id=searchType></span>\n'+
'</td></tr></table>\n';


gel('wxpCanvas').style.display='none';
var C;
(C=gel('adminCanvas')).style.display='';
C.innerHTML=html;

sysadmin.searchView='sysAdmin';
setTimeout(function(){showAdminSearch('users')},250);
checkAdminSearch();
ghostUser(0);
}































function showGroupAdmin(gid){

sysadmin.groupid=gid;
var html=
'<br/>'+
'<span id=adminTitle style="font:bold normal 16px Lucida,sans-serif">Loading</span><br/><br/>\n'+
'<table style="background-color:#ffffff;width:1002px;height:100%;"><tr><td align=left valign=top>\n'+
'['+iLink('showRegistry(1)','Back to Emails')+'&nbsp;'+
'| '+iLink('showAdminSearch(\'users\')','User List')+'&nbsp;'+
'| '+iLink('groupInviteUser('+gid+')','Invite Trustifi Subscriber')+'&nbsp;'+
'| '+iLink('createUser()','Invite New Subscriber')+'&nbsp;'+
'| '+iLink('askReport(\'group\')','Group Reporting')+']<br/>\n'+
'<span style="font:normal 12px Lucida,sans-serif" id=summary></span>\n'+
iLink('ghostUser(-1)','','ghostDisable')+'<br/>\n'+
'<span id=adminTable style="display:none"><input type=hidden name=searchType id=searchType></span>\n'+
'</td></tr></table>\n';


gel('wxpCanvas').style.display='none';
var C;
(C=gel('adminCanvas')).style.display='';
C.innerHTML=html;

sysadmin.searchView='groupAdmin';
setTimeout(function(){showAdminSearch('users')},250);
checkAdminSearch();
ghostUser(0);
}

function groupInviteUser(gid,em){

if(!em)em='';
var t='groupInviteUser.';
floatAsk(wtext(t+'title'),
wtext(t+'body',{GID:gid,EMAIL:em,GROUPNAME:getGroupById(profile.groups,gid).name}),
[buttonCancel(),
button(wtext('next'),'groupInviteUserDo('+gid+')')]
);
setTimeout("gel('email').focus()",250);
}

function groupInviteUserDo(gid){

var t='groupInviteUser.done.',
e=gel('email').value,
data='groupInviteUser='+e
+'&groupid='+gid
+'&wxpauth='+wxpauth;
fH();
floatProgress();
ckajax.getText(base(data),data,function(stat,statStr,resp){
fH()
if(resp.indexOf('Error: No such account')!=-1){
t='groupInviteUser.nouser.';
return floatAsk(wtext(t+'title'),wtext(t+'body',{EMAIL:e,GROUPNAME:getGroupById(profile.groups,gid).name}),
[buttonCancel(),button(wtext('next'),'fH();createUser('+gid+',\''+e+'\')')]);
}
if(resp.indexOf('Error: ')!=-1)
return floatError(resp);
adminSearch();
floatAsk(wtext(t+'title'),wtext(t+'body',{EMAIL:e,GROUPNAME:getGroupById(profile.groups,gid).name}),
[button(wtext('close'),'fC()')]);
});
}

function askReport(type){
var t='askReport.';
html='',
who='';
if(type=='firm')
who='Firm '+bold(b64dec(profile.firm.name));
else if(type=='group')
who='Group '+bold(getGroupById(profile.groups,sysadmin.groupid).name);
else if(type=='user')
who='User '+bold(wxpemail);

floatAsk(parseTmpl('Reporting for '+'{WHO}',{WHO:who}),
wtext(t+'body',{RTYPE:type}),
[buttonCancel(),
buttonS(wtext('next'),'submit0','askReportForm')]
);

if(type=='user'){
var op=gel('reportType').options;
for(var i=0;i<op.length;i++)
if(op[i].value=='general')
op[i]=null;
}

gel('custom_hide').style.display='none';
}
function askReportTimeChanged(){
gel('custom_hide').style.display=(getSelected('timePeriod')=='custom')?'':'none';
}
function askReportTypeChanged(){
}
function askReportDeliveryChanged(){
}
function askReportDo(){
floatProgress();

var rtype=getVal('rtype'),
per=getSelected('timePeriod'),
start=getVal('custom_start'),
end=getVal('custom_end'),
type=getSelected('reportType'),
del=getSelected('delivery'),
err=gel('askReportErr'),
data='report='+rtype
+'&groupid='+sysadmin.groupid
+'&period='+per
+'&start='+start
+'&end='+end
+'&type='+type
+'&del='+del;

if(per=='')return err.innerHTML='Select a time period';
if(type=='')return err.innerHTML='Select a report type';
if(del=='')return err.innerHTML='Select a delivery type';

if(del=='newwin'){
var F=gel('askReportNewWin');
F.action=APP+'?'+data;
fH();
return F.submit();
}

ckajax.getText(base(data),data,function(stat,statStr,resp){
fH();
blanketScreen();
floatShow(1);
if(resp.indexOf('Error:')!=-1)
return floatError(resp);

if(del=='email'){
var t='askReportDo.email.';
floatAsk(wtext(t+'title'),wtext(t+'body',{EMAIL:wxpemail}),
[button(wtext('close'),'fH()')]);
}
});
}

function adminTableLoading(){

gel('adminTable').style.display='none';
gel('adminTitle').innerHTML='<i>Loading...</i>';
}
function adminTableDone(){

gel('adminTable').style.display='';
}

function modInv(x,m){

if(x==0)
return 0;
var s=m,t=x;
var a=0,b=1;
while(t){
var q=Math.floor(s / t),r=s%t;
s=t,t=r;
var temp=a-b*q;
while(temp <0)
temp+=m;
temp%=m;
a=b,b=temp;
}
return a;
}
function decConfNum(n){

return 'Unscrambled:<br/>'+modInv(n,4294967291);
}
function padConfNum(n){

var m=1*1000*1000*1000;
while(n <m){
n='0'+n;
m /=10;
}
return n;
}

function ghostUser(id,gid){

if(id <0){
wxpemail=unescape(getCookie('wxpemail')).toLowerCase();
setCookie('wxpsuper=');
}
if(!id){
id=getCookie('wxpsuper');
return ghostAlert(id);
}

floatProgress();
var data='adminGhostUser='+id
+'&groupid='+(gid?gid:0)
+'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
fH();
if(resp.indexOf('Error: ')!=-1)
return floatError(resp);
ghostAlert(id);
showRegistry(1);
});
}

function ghostAlert(id){

if(id&&id!=''&&id!=-1){
gel('ghostDisable').innerHTML='Stop impersonating user #'+id;
alert('You are now impersonating user #'+id+'.');
}else{
gel('ghostDisable').innerHTML='';
}
}

function editContent(){

loadWebtext();
}
var lastTextR=null;
function loadWebtext(rev){

if(sysadmin.timeout)
clearTimeout(sysadmin.timeout);

adminTableLoading();

rev=rev?rev:0;
var data='adminListWebtext='+rev+
'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error: ')!=-1)
return alert(resp);
var R=parseResponse(resp);
if(R.error)
return alert('Error:\n'+R.error+'\n'+resp);
lastTextR=R;
drawContentTable(R);



});
}
function drawContentTable(R){


var html='<b>Edit Site Content</b><br/><br/>\n'+
iForm('submitContent()','contentForm')+
'<input type=hidden name=searchType id=searchType value=""/>\n'+
'<table class=pad>\n'+
'<tr>'+
'<th>Revision Date</th>'+
'<th>Who</th>'+
'<th>Comment</th>'+
'</tr>';
var REV=R.rev;
qTrN=0;qTrBg=['#ffffff','#f2f2f2'];
for(var i=0;i<REV.length;i++){
var datetime=REV[i].date,
who=REV[i].userid,
comment=b64dec(REV[i].comment);
if(!getUserById(who))
addUser({id:who,name:REV[i].name,email:REV[i].email});
html+=qTr(
td(floatTimeFull(datetime))+
td(floatUser(who))+
td(safeHTML(comment))
);
}

html+=
'</table>\n'+
'<br/><br/>\n'+
'<table class=pad>\n';

var two='';
var T=R.text;
for(var i=0;i<T.length;i++){
var tag=T[i].tag;
var val=b64dec(T[i].val);
if(tag=='meta.comment'){
html+='<tr id=contentRow'+i+' style="display:none"><td></td></tr>\n';
continue;
}
var val_safe=safeHTML(val);


var r=3,idx=0;
while((idx=val.indexOf('\n',idx+1))!=-1)
r++;

html+=two=qTrjs({id:'contentRow'+i},
td((i+1))+
td(tag)+
td('<span id=contentView'+i+'>'+iLink('toggleContent('+i+')',val_safe,'contentViewIn'+i)+'</span>\n'+
'<span id=contentEditClk'+i+' style="display:none">['+iLink('toggleContent('+i+')','Hide')+' | <a href="javascript:contentReset('+i+')">Reset</a>]<br/></span>\n'+
'<textarea id=contentEdit'+i+' name='+tag+' style="display:none" rows='+r+' cols=60 onblur="contentColorEdit('+i+')">'+val_safe+'</textarea>\n'
)
);
}


html+='<tr class='+qTrBg[(qTrN+=1)%qTrBg.length]+'>'+
'<td colspan=2>Revision Comment<br/>\n'+
'['+iLink('contentHideUnchanged()','Hide Unchanged')+' | <a href="javascript:contentShowAll()">Show All</a>]'+
'</td>'+
td('<textarea name=meta_comment id=meta_comment rows=10 cols=60></textarea>')+
'</tr>'+
'<tr class=tabRow3>'+
'<td colspan=3><input type=button value="Submit changes" onclick="submitContent();"></td>'
'</tr>'+
'</table>\n';



gel('adminTable').innerHTML=html;

adminTableDone();
}

function submitContent(){

var data='adminSubmitWebtext=1';
var f=gel('contentForm');
var e=f.elements;
for(var i=0;i<e.length;i++){
var n=e[i].name;
if(n=='searchType'||n=='')
continue;
data+='&'+n+'='+strReplace(escape(e[i].value),'+','%2b');
}
data+='&wxpauth='+wxpauth;

floatProgress();
ckajax.getText(base('adminSubmitWebtext=1'),data,function(stat,statStr,resp){
if(resp.indexOf('Error: ')!=-1)
return floatError(resp);

loadWebtext();
fH();
});
}

function contentReset(n){

gel('contentEdit'+n).value=b64dec(lastTextR.text[n].val);
contentColorEdit(n);
}

function contentShowAll(){

for(var i=0;true;i++){
var e=gel('contentRow'+i);
if(!e)
break;
e.style.display='';
}
}

function contentHideUnchanged(){

for(var i=0;true;i++){
var e=gel('contentRow'+i);
if(!e)
break;
if(contentCheckEdit(i)){
e.style.display='none';
}
}
}

function addCredits(email){

fC();
blanketScreen();

var t='addCredits.ask.',
data='adminGetUsersGroups='+escape(email)
+'&wxpatuh='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
fC();
if(resp.indexOf('Error:')!=-1)
return floatError(resp);

var R=parseResponse(resp),
G={'0':'Personal Credits'};
R=R.group;
if(R)for(var i=0;i<R.length;i++)
G[''+R[i].id]=b64dec(R[i].name);

floatAsk(wtext(t+'title'),
wtext(t+'body',{EMAIL:email,GROUPSEL:dropDownArr('groupCredits',G,0,0,0,1)}),
[buttonCancel(),button(wtext('next'),'addCreditsDo()')]
);
});
}

function addCreditsDo(){

var e=gel('email').value;
if(e.length==0)
return floatError(wtext('addCredits.error.noemail'));

floatProgress();

var credits=getVal('credits'),
subtotal=getVal('subtotal');

if(credits <0||subtotal <0){
fH();
return alert('Cannot use negative values,yet');
}

var data='adminAddCredits=1'
+'&credits='+credits
+'&subtotal='+subtotal
+'&email='+escape(e)
+'&groupcredits='+getSelected('groupCredits')
+'&wxpauth='+wxpauth;

ckajax.getText(base(data),data,function(stat,statStr,resp){
fH();
var t='addCredits.error.';
if(resp.indexOf('Error')!=-1)
return floatError(resp);
showAdminSearch('purchases');
});
}

function createUser(gid,email){
debug('createUser('+gid+')');
if(gid)
sysadmin.groupid=gid;
fC();
var t='createUser.ask.';
editProfile('createUser.fillProfile');
if(email)gel('email').value=email;
if(gel('getpostmarkemail'))gel('getpostmarkemail').checked=true;
}

function createUserBulk(){

var t='createUserBulk.',
html=wtext(t+'body',{WXPAPPURL:SYSINFO.appurl,GROUPID:profile.group.groupid});
floatAsk(wtext(t+'title'),
html,
[buttonCancel(),
button(wtext('next'),'createUserBulkDo()')]
);
}

function createUserDo(){

var o,msg=gel('editProfileMsg');

checkField(o=gel('email'),alphaemail,128);
if(o.value.length==0){
cFH(o);
return msg.innerHTML=wtext('purchaseCredits.error.email');
}

checkField(o=gel('firstname'),lets,30);
if(o.value.length==0){
cFH(o);
return msg.innerHTML=wtext('purchaseCredits.error.firstname');
}

checkField(o=gel('lastname'),lets,30);
if(o.value.length==0){
cFH(o);
return msg.innerHTML=wtext('purchaseCredits.error.lastname');
}

checkField(o=gel('city'),lets,30);
if(o.value.length==0){
cFH(o);
return msg.innerHTML=wtext('purchaseCredits.error.city');
}

if(getSelected('province')==''){
cFH(gel('province'));
return msg.innerHTML=wtext('purchaseCredits.error.province');
}

floatProgress();

var groupid=sysadmin.groupid!=-1?sysadmin.groupid:0,
data='adminCreateUser=1'
+'&view='+sysadmin.searchView
+'&groupid='+groupid
+'&email='+escape(getVal('email'))
+'&firstname='+escape(getVal('firstname'))
+'&lastname='+escape(getVal('lastname'))
+'&address='+escape(getVal('address'))
+'&address2='+escape(getVal('address2'))
+'&city='+escape(getVal('city'))
+'&province='+getSelected('province')
+'&country='+getSelected('country')
+'&postalcode='+escape(getVal('postalcode'))
+'&phonenum='+getVal('phonenum')
+'&getpostmarkemail='+getCheckedValue('getpostmarkemail')
+'&wxpauth='+wxpauth;
ckajax.getText(base(data),data,function(stat,statStr,resp){
fH();
if(resp.indexOf('already exists')!=-1){
var t='createUser.userExist.';
return floatAsk(wtext(t+'title'),wtext(t+'body'),
[buttonCancel(),button(wtext('next'),'groupInviteUser('+groupid+',\''+getVal('email')+'\')')]
);
}
if(resp.indexOf('Error')!=-1)return floatError(resp);

var t='createUser.';
if(groupid==-1)t='createUser.sysadmin.';
floatAsk(wtext(t+'title'),
wtext(t+'body',{EMAIL:getVal('email'),WXPNANE:SYSINFO.name}),
[button(wtext('close'),'fH()')]
);

if(sysadmin.firmid!=-1)showAdminSearch('groups');
else showAdminSearch('users');
});
}


function showRegistry(jump){


gel('wxpCanvas').style.display='';
gel('adminCanvas').style.display='none';
if(sysadmin.timeout)clearTimeout(sysadmin.timeout);
if(jump)tree_loadData();
}
function showAdminSearch(type){
gel('searchType').value=sysadmin.searchType=type;
adminSearch();
}
function showEndOfDay(batchnum,off){

if(batchnum!=null)
gel('batchnum').value=batchnum;
gel('searchType').value='endOfDay';
adminSearch(off);
}
function showClerkFiles(){

gel('searchType').value='clerkFiles';
adminSearch();
}

function getHostname(ip){
if(!getHostname.arr)getHostname.arr=[];


if(getHostname_show(ip))return;

var arr=gelt('a');
for(var i=0;i<arr.length;i++){
var A=arr[i];
if(A.id&&A.id==('ip'+ip))
A.innerHTML='<img src=i/loading.gif />'+A.innerHTML;
}

var data='adminGetHostname='+ip
+'&wxpauth='+wxpauth;
if(sysadmin.searchView=='groupAdmin')
data+='&groupid='+sysadmin.groupid;
ckajax.getText(base(data),data,function(stat,statStr,resp){
getHostname.arr[ip]=resp==ip?'<i>not in DNS</i>':resp;
getHostname_show(ip);
});
}
function getHostname_show(ip){

var host=getHostname.arr[ip];
if(!host)
return false;

var arr=gelt('a'),
F=function(s){return s.substring(s.indexOf('>')+1);};
for(var i=0;i<arr.length;i++){
var A=arr[i];
if(A.id&&A.id==('ip'+ip)){
A.href='#';
A.onclick=function(){return false;};
A.innerHTML=floatText(host,ip);
}
}

return true;
}
function getHostname_showAll(){

for(var ip in getHostname.arr)
getHostname_show(ip);
}

function filterIp(ip){

gel('user_ip').value=ip;
adminSearch();
}

function getVal2(e){

var f=gel(e),
c=getCookie(e);
if(f){
if(f.type=='checkbox')
return f.checked;
var v=f.value;
if(!v)
v=f.innerHTML;
return v;
}

return c;
}

function showSummary(S){

var html='Updated: '+local(time())+'<br/>'+
'Users: '+S.users+'<br/>'+

'Folders: '+S.folders+'<br/>'+
'Projects: '+S.projects+'<br/>'+
'Credits Sold: '+(S.epmQuantity/100)+'<br/>'+
'Credits Outstanding: '+(S.epmOutstanding/100)+'<br/>'+
'Current EPM Balance: '+S.epmBalance+'<br/>'+
'Revenue: $'+dec2(S.epmRevenue)+'<br/>'+
'';

gel('summary').innerHTML=html;
}

function clerkGhostUser(i){
var t='clerkGhostUser.',
C=profile.clients[i],
data='clerkGhostUser='+(i==-1?-1:C.id)
+'&wxpauth='+wxpauth;
floatProgress();
ckajax.getText(base(data),data,function(stat,statStr,resp){
if(resp.indexOf('Error: ')!=-1)
return floatError(resp);
showMain();
floatAsk(wtext(t+'title'),
(i==-1)?wtext(t+'body.end'):wtext(t+'body',{EMAIL:C.email}),
[button(wtext('close'),'fH()')]
);
});
}

function adminSearch(off,len){

if(sysadmin.timeout)
clearTimeout(sysadmin.timeout);

adminTableLoading();
if(!gel('searchType')){
if(sysadmin.groupid!=-1)showGroupAdmin();
else showAdmin();
}

var action='',
type=gel('searchType').value;
if(type=='users')action='adminListUsers=1';
else if(type=='logins')action='adminListLogins=1';
else if(sysadmin.groupid!=-1&&type=='files')action='groupListFiles=1';
else if(sysadmin.firmid!=-1&&type=='files')action='firmListFiles=1';
else if(type=='files')action='adminListFiles=1';
else if(sysadmin.groupid!=-1&&type=='purchases')action='groupListPurchases=1';
else if(type=='purchases')action='adminListPurchases=1';
else if(type=='endOfDay')action='adminGetEndOfDay=1';
else if(type=='errors')action='adminListErrors=1';
else if(type=='errors_user')action='adminListUserErrors=1';
else if(type=='errors_email')action='adminListEmailErrors=1';
else if(type=='tracking')action='adminListTracking=1';
else if(type=='groups')action='firmListGroups=1';
else action='unknownAction=1';

if(!off)
off=-1;
if(!len)
len=-1;

firmid=(sysadmin.searchView=='firmAdmin')?profile.firm.id!=-1:'';

var data=action
+'&view='+sysadmin.searchView
+'&name='+getVal2('user_name')
+'&groupid='+sysadmin.groupid
+'&firmid='+firmid
+'&start='+getVal('start','')
+'&end='+getVal('end','')
+'&groupname='+getVal2('user_groupname')
+'&email='+getVal2('user_email')
+'&recipemail='+getVal2('user_recipemail')
+'&cardnum4='+getVal2('user_cardnum4')
+'&failed='+getVal2('user_failed')
+'&noguest='+getVal2('user_noguest')
+'&ip='+getVal2('user_ip')
+'&hostname='+getSelected('user_hostname')
+'&epm='+getVal2('user_epm')
+'&confnum='+getVal2('user_confnum')
+'&agent='+getVal2('user_agent')
+'&referrer='+getVal2('user_referrer')
+'&filename='+getVal2('user_filename')
+'&loginerr='+getVal2('user_loginerr')
+'&uploaderr='+getVal2('user_uploaderr')
+'&message='+getVal2('user_message')
+'&batchnum='+getVal2('batchnum')
+'&off='+off
+'&len='+len
+'&wxpauth='+wxpauth;

ckajax.getText(base(data),data,function(stat,statStr,resp){
wxpauth=getCookie('wxpauth');
if(stat!=200)
return adminTableDone(floatError('http status='+stat+'/'+statStr));
if(resp.indexOf('Error: ')!=-1)
return adminTableDone(floatError(resp));
var R=parseResponse(resp);
if(R.error)
return adminTableDone(alert('Error:\n'+R.error+'\n'+resp));

if(R.summary)
showSummary(R.summary[0]);

gel('adminTable').innerHTML='';
gel('adminTable').k=0;

if(type=='endOfDay'){
if(R.approved)
drawUserTable(type,R.approved,R.range[0]);
if(R.failed)
drawUserTable(type,R.failed,R.range[0]);
if(R.batch)
drawUserTable('endOfDayBatch',R.batch,R.range[0]);
}
else if(type.indexOf('error')!=-1)drawUserTable(type,R.err,R.range[0],R);
else if(type=='groups')drawUserTable(type,R.group,R.range[0],R);
else if(type=='tracking')drawUserTable(type,R.track,R.range[0],R);
else if(type=='purchases')drawUserTable(type,R.purchase,R.range[0],R);
else{
if(type=='users'&&R.user)quicksort(R.user,function(a,b){return b.created*1-a.created*1;});
drawUserTable(type,R.user,R.range[0]);
}

var arr=data.split('&');
for(var i=0;i<arr.length;i++){
var kv=arr[i].split('=');
var e=gel('user_'+kv[0]);
if(kv[0]=='ip')kv[1]=long2ip(ip2long(kv[1]));
if(e)
e.value=kv[1];
}

getHostname_showAll();


if(sysadmin.groupid==-1)
sysadmin.timeout=setTimeout(adminSearch,10*60*1000);
});
}

function contentCheckEdit(n){

var e=gel('contentEdit'+n);
return !e?false:e.value==b64dec(lastTextR.text[n].val);
}
function contentColorEdit(n){

gel('contentRow'+n).style.background=contentCheckEdit(n)?'':'#ffcccc';
}
function toggleContent(n){

var view=gel('contentView'+n),
edit=gel('contentEdit'+n),
editClk=gel('contentEditClk'+n);

contentColorEdit(n);

var s=view.style;
s.display=(s.display=='')?'none':'';
var s=edit.style;
s.display=(s.display=='')?'none':'';
var s=editClk.style;
s.display=(s.display=='')?'none':'';
}

function toggleFullAddr(n){

var s=gel('fullAddr'+n).style;
s.display=(s.display=='')?'none':'';
}

function toggleTrace(n){

var s=gel('trace'+n).style;
s.display=(s.display=='')?'none':'';
}

function toggleFullReceipt(n){

var s=gel('receipt'+n).style;
s.display=(s.display=='')?'none':'';
}

function toggleFullResponse(id){

var s=gel('respmsg'+id);
if(!s)return;
var l=gel('resp'+id);
if(!l)return;
var d=gel('respdec'+id);
if(!d)return;

if(d.innerHTML==''){
d.innerHTML='<xmp>'+b64dec(l.innerHTML)+'</xmp>';
}
else if(d.style.display==''){
s.style.display='';
d.style.display='none';
return;
}
s.style.display='none';
d.style.display='';
}

function toggleAddr(id){

var o=gel('addr'+id);
var s=o.style;
s.display=(s.display=='')?'none':'';
}

function toggleCardCrypt(id){

var o=gel('cardcrypt'+id),
s=o.style;
if(s.display==''){
s.display='none';
gel('cardcryptmsg'+id).style.display='';
}else{
s.display='';
gel('cardcryptmsg'+id).style.display='none';
}
}

function adminTitle(str,R){
var add='System Admin';
if(sysadmin.firmid!=-1)
add='Firm-'+b64dec(profile.firm.name);
if(sysadmin.groupid!=-1){
if(!R||!R.group)R=profile.groups;
add='Group-'+getGroupById(R,sysadmin.groupid).name;
}
gel('adminTitle').innerHTML=str+'-'+add;
}

function drawUserTable(type,arr,range,R){

adminTableLoading();
if(!arr)
arr=[];

var ut=gel('adminTable'),
ng=getVal2('user_noguest')=='true',
head=[
['ID',iSubmit()],
['Email&nbsp;[<label for=user_noguest>No Guests:</label><input type=checkbox id=user_noguest name=user_noguest onchange="setCookie(\'user_noguest='+!ng+'\');adminSearch();" '+(ng?'CHECKED':'')+'>]',
iText('user_email')],
['Name',iText('user_name')]
],
ehead=[],
hosts=[],
t=['hydrogen','helium','lithium','beryllium'];

for(var i=0;i<t.length;i++)
hosts[t[i]]=t[i];

if(type=='users'){
adminTitle('Users',R);
ehead=[
head[0],
head[1],
head[2],
['Group',''],
['Joined','Local Time'],
['Quick Stats','$$$ / Bought / Used / Left'],
['IP Addr',iText('user_ip','','100px')]
];
head=[];
}
else if(type=='groups'){
adminTitle('Firm Groups',R);
head=[
['Group','']
];
}
else if(type=='logins'){
adminTitle('User Logins',R);
ehead=[
['Browser',iText('user_agent','','100px')],
['Login At','Local Time'],
['IP Addr',iText('user_ip','','100px')],
['Hostname',dropDownArr('user_hostname',hosts,'adminSearch()',getSelected('user_hostname'))]
];
}
else if(type=='files'){
adminTitle('Uploaded Files',R);
ehead=[
['File Size',''],

['Uploaded','Local Time'],
['Postmarked','Local Time'],
['EPM Tran',iText('user_epm','','100px')],
['IP Addr',iText('user_ip','','100px')]
];
}
else if(type=='purchases'){
var uf=getVal2('user_failed')=='true';
adminTitle('Purchase Log',R);
head=[
['',iSubmit()],
['Confirmation',iText('user_confnum','100px')],
['Email',iText('user_email')],
['Name',iText('user_name')],

['Date/Time','Local Time'],
['IP Addr',iText('user_ip','','100px')],
['CardNum',iText('cardnum4','','50px')],
['Credits',''],
['Amount','<input type=checkbox id=user_failed name=user_failed onchange="setCookie(\'user_failed='+!uf+'\');adminSearch();" '+(uf?'CHECKED':'')+'><label for=user_failed>Failed</label>'],
['Address','&nbsp;']
];
}
else if(type=='tracking'){
adminTitle('Tracking',R);
head=[
['ID',iSubmit()],
['Event Type',''],
['User Email',iText('user_email')],
['Recip Email',iText('user_recipemail')],
['Filename',iText('user_filename')],
['Error At','Local Time'],
['IP Addr',iText('user_ip','','100px')],
['Browser',iText('user_agent','','100px')],
['Referrer',iText('user_referrer','','100px')]
];
}
else if(type.indexOf('errors')!=-1){
head=[
['ID',iSubmit()],
['User ID',''],
['Email',iText('user_email')],
['Name',iText('user_name')],
['Error At','Local Time'],
['IP Addr',iText('user_ip','','100px')],
['Hostname',dropDownArr('user_hostname',hosts,'adminSearch()',getSelected('user_hostname'))],
['Browser',iText('user_agent','','100px')],
['Message&nbsp[No Err:&nbsp;'+
'<label for=user_loginerr>Logins:</label><input type=checkbox id=user_loginerr name=user_loginerr onchange="adminSearch();" '+(getVal2('user_loginerr')?'CHECKED':'')+'>'+
'<label for=user_uploaderr>Uploads:</label><input type=checkbox id=user_uploaderr name=user_uploaderr onchange="adminSearch();" '+(getVal2('user_uploaderr')?'CHECKED':'')+'>]',
iText('user_message')]
];
if(type=='errors')
adminTitle('Server-side User Errors',R);
if(type=='errors_user')
adminTitle('Browser-side User Errors',R);
if(type=='errors_email'){
adminTitle('Email Processing Errors',R);
head.splice(7,1,['Email Client',iText('user_agent','','100px')]);
head.splice(3,1);
head.splice(2,1,['From',iText('user_email')]);
head.splice(1,1);
}
}
else if(type=='endOfDay'){
adminTitle('EndOfDay '+(ut.k==0?'Payments':'Failures'),R);
head=[
['Processed<br/>UTC Time',''],
['Result',''],
['OrderID',''],
['User',''],
['IP Addr',''],
['Credits',''],
['Paid',''],
['Name on Card',''],
['Address',''],
['Payment Via','']
];
}
else if(type=='endOfDayBatch'){
adminTitle('EndOfDay Batch Listing',R);
head=[
['BatchNum',''],
['Begining',''],
['Ending',''],
['Status',''],

['Success',''],
['Failed',''],
['Credits<br/>Bought',''],
['Credits<br/>Issued',''],
['Credits<br/>Used',''],
['Credits<br/>Balance',''],
['EPM<br/>Purchased',''],
['EPM<br/>Balance',''],
['Projects',''],
['Users<br/>New',''],
['Users<br/>Total',''],
['Users<br/>Invited',''],
['Users<br/>Trial',''],
['SubTotal',''],
['PST',''],
['GST',''],
['Revenue',''],
['Revenue<br/>MC',''],
['Revenue<br/>Visa',''],
['Revenue<br/>Other','']
];
}
else{
adminTitle('Unknown search type',R);
}

range.off *=1;
range.len *=1;
var adminSearchJS=function(o,l){return 'adminSearch('+(o?(o+','+l):'')+')'; },
rangeHtml=
iLink(adminSearchJS(range.off-range.len,range.len),'Prev')+'&nbsp;'+

'['+(range.off+1)+' .. '+(range.off+range.len)+']&nbsp;'+
iLink(adminSearchJS(range.off+range.len,range.len),'Next')+'&nbsp;'+

'<br/>';
if(type=='endOfDay')
rangeHtml='';
var html='';
if(type=='purchases')
html+='<table><tr>'+td('Start:')+td(iCal('start',iCalMonthStart()))+'</tr>'+
'<tr>'+td('End:')+td(iCal('end',iCalMonthEnd()))+'</tr></table>';
html=
rangeHtml+
iForm(adminSearchJS())+
iHide('searchType',strReplace(type,'Batch',''))+

iHide('batchnum',getVal2('batchnum'))+

'<table class=pad style="width:100%">'+
'<tr class=head><td></td>';
for(var i=0;i<ehead.length;i++)
head.push(ehead[i]);

if(type=='users'){
if(sysadmin.searchView=='groupAdmin'){
head.splice(5,3,['Group Credits','Purchsed / Balance'],['Group Credits Used','']);
head.splice(3,1,['Role','']);
head.splice(0,1);
}
else if(sysadmin.searchView=='sysAdmin'){

head.splice(3,1);
head.splice(1,0,['Credits','']);
}
}

for(var i=0;i<head.length;i++)
html+=tdt(head[i][0]);
html+='</tr>'+
'<tr class=head><td>'+iSubmit()+'</td>';
for(var i=0;i<head.length;i++)
html+=(head[i][0]=='IP Addr')?tdr(head[i][1]):tdt(head[i][1]);
html+='</tr>';

qTrN=0;qTrBg=['#ffffff','#f2f2f2'];
for(var i=0;i<arr.length;i++){
if(type=='logins')html+=drawUserTableRow_login(arr,i,range.off+i+1);
else if(type=='groups')html+=drawUserTableRow_group(arr,i,range.off+i+1,R);
else if(type=='files')html+=drawUserTableRow_file(arr,i,range.off+i+1);
else if(type=='purchases')html+=drawUserTableRow_purchase(arr,i,range.off+i+1);
else if(type=='endOfDay')html+=drawUserTableRow_endOfDay(arr,i,range.off+i+1);
else if(type=='endOfDayBatch')html+=drawUserTableRow_endOfDayBatch(arr,i,range.off+i+1);
else if(type.indexOf('errors')!=-1)html+=drawUserTableRow_error(arr,i,range.off+i+1);
else if(type=='tracking')html+=drawUserTableRow_tracking(arr,i,range.off+i+1);
else html+=drawUserTableRow_user(head,arr,i,range.off+i+1);
}

html+='</table>'+
'</form><br/><hr><br/>';

ut.innerHTML+=html;

qTrColour();

ut.k+=arr.length;

adminTableDone();
}

function drawUserTableRow_user(head,arr,i,I){

var R=arr[i],
g=sysadmin.groupid,
disabled=(!isGroupAdmin(g)&&!isSysAdmin(g))||(1*R.groupid)==-1,
groupAdmin=td(
dropDownArr('userGroupType'+R.userid,{inactive:'inactive',user:'user',admin:'admin'},"updateGFType('Group',"+R.userid+",'"+R.email+"')",R.grouptype,disabled)),


creditsHtml=dec2(R.credBought),
gh='';

if(sysadmin.searchView=='sysAdmin'&&R.userid>0){
gh=' ('+iLink('ghostUser('+R.userid+')','Clerk')+')';
creditsHtml='('+iLink('addCredits(\''+R.email+'\')',creditsHtml)+')';
}

i+=gel('adminTable').k;

if(!isGroupAdmin())groupAdmin=td('');
if(R.firmname=='')
R.firmname='<span style="font-style:italic;color:#cccccc">none</span>';
var tdstr=td(I);
R.ip=long2ip(R.ip);
for(var j=0;j<head.length;j++){
var h=head[j][0];
if(h=='ID')tdstr+=tdr(R.userid+(R.userid==getUserId()?'':gh));
if(h=='Credits')tdstr+=tdr(creditsHtml);
if(h.indexOf('Email')==0)tdstr+=td(R.email+(R.verified=='NOT'?'&nbsp;[<span style="color:red">Not Verified</span>]':''));
if(h=='Name')tdstr+=td(b64dec(R.name));
if(R.userid>0){
if(h=='Role')tdstr+=groupAdmin;
if(h=='Joined')tdstr+=td(floatTimeFull(R.created));
if(h=='Quick Stats')tdstr+=td(floatUserStats(R));
if(h=='Group Credits')tdstr+=td(floatUserStats(R));
if(h=='Group Credits Used')tdstr+=td(floatUserStats(R,1));
if(h=='IP Addr')tdstr+=tdr(iLink("getHostname('"+R.ip+"')",R.ip,'ip'+R.ip)+'['+iLink("filterIp('"+R.ip+"')",'Filter')+']');
}
else if(h=='Joined'||h=='Role')tdstr+=td('Pending Acceptance');
}
return qTrjs({over:"noteRowOver(this)",sty:R.userid<0?'color:#aaaaaa':null},tdstr);
}

function updateGFType(gf,id,email){

var t='update'+gf+'Type.',
ef=gel('userFirmType'+id),
eg=gel('userGroupType'+id),
type=getSelected('user'+gf+'Type'+id),
data='adminUpdate'+gf+'Type='+id
+'&groupid='+sysadmin.groupid
+'&firmid='+sysadmin.firmid
+'&type='+type
+'&wxpauth='+wxpauth;
if(type=='')
return;

adminTableLoading();

ckajax.getText(base(data),data,function(stat,statStr,resp){
if(ef)ef.disabled=false;
eg.disabled=false;
adminTableDone();
if(resp.indexOf('Error: ')!=-1){
floatError(resp);
}else{
floatAsk(wtext(t+'title'),wtext(t+'body',{EMAIL:email,TYPE:type}),
[button(wtext('close'),'fH()')]
);
}
adminSearch();
});
}

function drawUserTableRow_file(arr,i,I){

var R=arr[i],
name=b64dec(R.name);

fLink++;
return qTrjs({over:"noteRowOver(this)"},
td(I)+
td(R.userid)+
td(R.email)+
td(floatTruncText(name,20))+
td(humanSize(R.size))+

td(floatTimeFull(R.created))+
td(floatTimeFull(R.postmarkdate))+
td(fixWidth(R.epmtrankey))+
tdr(iLink("getHostname('"+R.ip+"')",R.ip,'ip'+R.ip)+'['+iLink("filterIp('"+R.ip+"')",'Filter')+']')
);
}

function drawUserTableRow_group(arr,i,I,RR){

var R=arr[i],
ret='',
ut=gel('adminTable'),
utab='',
uhead='',
i=ut.k,
head=[
['ID',''],
['Role',''],
['Email',''],
['Name',''],
['Updated','']
];
for(var j=0;j<head.length;j++)
uhead+=' <th valign=top>'+head[j][0]+'</th>';



var saveN=qTrN;qTrN=0;
moveUser_groups=RR.group;
for(var j=0,k=0;j<RR.user.length;j++){
var U=RR.user[j];
if(U.groupid!=R.id)
continue;
var J=++ut.k;
utab+=qTrjs({over:"noteRowOver(this)"},
tdr(U.id+' ('+iLink('ghostUser('+U.id+')','Clerk')+')('+iLink('moveUserGroup('+R.id+','+U.id+')','Move')+')')+
td(dropDownArr('userGroupType'+U.id,{remove:'Remove',user:'user',admin:'admin'},"updateGFType('Group',"+U.id+",'"+U.email+"')",U.type))+
td(U.email)+
td(b64dec(U.name))+
td(floatTimeFull(U.created))

);
}

qTrN=saveN;
ret=qTrjs({clk:"toggleHidden('groupTab"+i+"')",over:"noteRowOver(this)"},
td(I)+
tdr(R.name+'&nbsp;'+
floatMenu('Actions',[
iLink('firmRenameGroup('+R.id+')','Rename'),
iLink('groupInviteUser('+R.id+')','Invite User'),
iLink('createUser('+R.id+')','Create User')
])
)+
'</tr>'+
'<tr id=groupTab'+i+' style="display:none" id=groupTab'+i+'>'+td('')+td(
'<table class=pad style="width:100%;">'+
'<tr class=head>'+uhead+'</tr>'+
utab+
'</table>'
)
);

ut.k+=RR.user.length;

return ret;
}

function drawUserTableRow_login(arr,i,I){

var R=arr[i],
ua=floatUserAgent(b64dec(R.useragent),i),
gh='';
if(sysadmin.searchView=='sysAdmin')
gh=' ('+iLink('ghostUser('+R.userid+')','Clerk')+')';

return qTrjs({over:"noteRowOver(this)"},
td(I)+
tdr(R.userid+gh)+
td(R.email)+
td(b64dec(R.name))+
td(ua)+
td(floatTimeFull(R.date))+
tdr(iLink('getHostname(\''+R.ip+'\')',R.ip,'ip'+R.ip)+
'['+iLink('filterIp(\''+R.ip+'\')','Filter')+']')+

td(R.hostname)
);
}

function drawUserTableRow_error(arr,i,I){

var R=arr[i];
if(!R.useragent)R.useragent='';
if(!R.message)R.message='';

var msg=b64dec(R.message);
if(!R.trace){
var idx;
R.trace='';
if((idx=msg.indexOf('<br>'))!=-1){
R.trace=msg.substr(idx+4);
msg=msg.substr(0,idx+4);
}
else if((idx=msg.indexOf('<br/>'))!=-1){
R.trace=msg.substr(idx+5);
msg=msg.substr(0,idx+5);
}
}else{
R.trace=b64dec(R.trace);
}
R.message=msg;

R.ip=long2ip(R.ip);

var type=0;
if(sysadmin.searchType=='errors'){
type=0;
R.trace='<xmp>'+R.trace+'</xmp>';
}
else if(sysadmin.searchType=='errors_user'){
type=1;
}
else if(sysadmin.searchType=='errors_email'){
type=2;
}

var TDs=td(I)+td(R.id);
if(type!=2)TDs+=tdr(R.userid+' ('+iLink('ghostUser('+R.userid+')','Clerk')+')');
TDs+=td(R.email);
if(type!=2)TDs+=td(b64dec(R.name));
TDs+=td(floatTimeFull(R.date))+
tdr(iLink('getHostname(\''+R.ip+'\')',R.ip,'ip'+R.ip)+
'['+iLink('filterIp(\''+R.ip+'\')','Filter')+']')+

td(R.hostname)+
td(floatUserAgent(b64dec(R.useragent)))+
td(iLink('toggleTrace('+R.id+')',R.message)+'<span id=trace'+R.id+' style="display:none">'+strReplace(R.trace,'\t',' ')+'</span>');
return qTrjs({over:"noteRowOver(this)"},TDs);
}

function drawUserTableRow_tracking(arr,i,I){

var R=arr[i];
if(!R.useragent)R.useragent='';
R.ipaddr=long2ip(R.ipaddr);
if(!R.referrer)R.referrer='';
return qTrjs({over:"noteRowOver(this)"},
td(I)+
td(R.id)+
tdr(R.item)+

td(R.useremail+'&nbsp;')+

td(R.recipemail+'&nbsp;')+

td(floatTruncText(b64dec(R.filename),15)+'&nbsp;')+
td(floatTimeFull(R.datetime))+
tdr(iLink('getHostname(\''+R.ipaddr+'\')',R.ipaddr,'ip'+R.ipaddr)+
'['+iLink('filterIp(\''+R.ipaddr+'\')','Filter')+']')+
td(floatUserAgent(b64dec(R.useragent)))+
td(floatReferrer(b64dec(R.referrer)))
);
}

function floatUserStats(R,extra){

fLink++;

var s,l;
if(sysadmin.groupid==-1){
s='$'+[dec2(R.spent),R.credBought/100,R.credUsed/100,R.credLeft/100].join(' / ');
l='Credits Bought: '+(R.credBought/100)+'<br/>'+
'Credits Used: '+(R.credUsed/100)+'<br/>'+
'Credits Left: '+(R.credLeft/100)+'<br/>'+
'Folders: '+R.folders+'<br/>'+
'Projects: '+R.projects+'<br/>'+
'';
}else{
s=extra?(R.credUsed/100):[R.credBought/100,R.credLeft/100].join(' / '),
l='Group Credits<br/>'+
'Bought: '+(R.credBought/100)+'<br/>'+
'Used: '+(R.credUsed/100)+'<br/>'+
'Left: '+(R.credLeft/100)+'<br/>'+
'';
}

return '<span class=floatUser id=fLink'+fLink+' '+
'onmouseover="floatNearShow('+fLink+',unescape(\''+escape(l)+'\'))" '+
'onmouseout="floatHide2()">'+s+'</span>';
}
function floatConfNum(n){

fLink++;
n=modInv(n,4294967291);
return '<span class=floatUser id=fLink'+fLink+' '+
'onmouseover="floatNearShow('+fLink+',decConfNum('+n+'))" '+
'onmouseout="floatHide2()">'+padConfNum(n)+'</span>';
}

function drawUserTableRow_purchase(arr,i,I){

var R=arr[i];
R.result=b64dec(R.result);
var fullTxn=R.result,
confnum=R.confnum,
errsty=R.result=='Approved'?'':'color:#ff0000';
fullTxn+='\n'+b64dec(R.receipt)+'\n'+b64dec(R.responseData);

if(R.cardnum4=='TRFI')R.cardnum4='Trustifi';

var html=
qTrjs({over:'noteRowOver(this)',sty:errsty},
'<td></td>'+
td(I)+
tdr(floatConfNum(confnum))+
td(R.email)+
td(b64dec(R.name))+

td(floatTimeFull(R.date))+
tdr(iLink('getHostname(\''+R.ip+'\')',R.ip,'ip'+R.ip)+
'['+iLink('filterIp(\''+R.ip+'\')','Filter')+']')+

td(
iLink('toggleFullReceipt('+confnum+')','xxxx-xxxx-xxxx-'+R.cardnum4)+
'<span style="display:none" id=receipt'+confnum+'><xmp>'+fullTxn+'</xmp></span>'
)+
tdr(dec2(R.credits))+
tdr(dec2(R.value)+' '+currencyAcro(R.currency))+
td(
iLink('toggleFullAddr('+confnum+')',R.address)+
'<span style="display:none" id=fullAddr'+confnum+'><br />'+
R.city+'<br />'+
R.province+'<br />'+
R.country+'<br />'+
R.postalcode+'<br />'+
R.phonenum+
'</span>'
)
);

return html;
}

function drawUserTableRow_endOfDayBatch(arr,i,I){

var R=arr[i];
i+=gel('adminTable').k;
var off=I-i-1;

var html=qTrjs({over:"noteRowOver(this)"},
td('')+
td(iLink('showEndOfDay('+R.batchnum+','+off+')',dec6(R.batchnum)))+
td(floatTimeFull(1*R.begining+1))+
td(floatTimeFull(R.ending))+
td(strReplace(b64dec(R.procStatusMessage),'{none}','&nbsp;'))+

tdr(R.count)+
tdr(R.failcount)+
tdr(dec2(R.creditsPurchased))+
tdr(dec2(R.creditsGiven))+
tdr(dec2(R.creditsUsed))+
tdr(dec2(R.creditsBalance))+
tdr(R.epmPurchased)+
tdr(R.epmBalance)+
tdr(R.projectsTotal)+
tdr(R.usersNew)+
tdr(R.usersTotal)+
tdr(R.usersWaiting)+
tdr(R.usersTrial)+
tdr(dec2(R.subtotal))+
tdr(dec2(R.pst))+
tdr(dec2(R.gst))+
tdr(dec2(R.revenue))+
tdr(dec2(R.revenueMC))+
tdr(dec2(R.revenueVISA))+
tdr(dec2(R.revenueGIFT))
);

return html;
}

function drawUserTableRow_endOfDay(arr,i,I){

var R=arr[i];
i+=gel('adminTable').k;
var id=R.confnum;
var ct=R.cardtype;
ct=ct?(ct.substr(0,1)+'-'):'';
var cardcrypt='';
for(var j=0;j<R.cardcrypt.length;j+=64)
cardcrypt+=R.cardcrypt.substr(j,64)+'<br/>\n';
var ip=long2ip(R.ipaddr);

if(R.cardnum4=='TRFI'){
ct='';
R.cardnum4='Trustifil';
}

var html=
qTrjs({over:"noteRowOver(this)"},
'<td></td>'+
'<td valign=top style="font:normal 12px Courier New,monospace;">'+floatTimeFull(R.procdate)+'</td>'+
tdt(
iLink('toggleFullResponse('+id+')',
'<span id=respmsg'+id+'>'+b64dec(R.result)+'</span>'+
'<span id=respdec'+id+'></span>'+
'<span id=resp'+id+' style="display:none">'+R.responseData+'</span>'
)
)+
tdtr(id)+
tdt(R.email)+
tdtr(iLink('getHostname(\''+ip+'\')',ip,'ip'+ip))+
tdtr(dec2(R.quantity))+
tdtr('$'+dec2(1*R.subtotal+1*R.pst+1*R.gst)+' '+R.currency)+
tdt(R.cardname)+
tdt(
iLink('toggleAddr('+id+')',
R.address+'<span id=addr'+id+' style="display:none"><br/>'+
R.city+'<br/>'+
R.province+'<br/>'+
R.country+'<br/>'+
R.postalcode+'<br/>'+
R.phonenum+'</span>'
)
)+
tdt(
iLink('toggleCardCrypt('+id+')',
'<span id=cardcryptmsg'+id+'>'+ct+R.cardnum4+'</span>'+
'<span id=cardcrypt'+id+' style="font:normal 12px Courier New,monospace;display:none">'+
cardcrypt+
'</span>'
)
)
);

return html;
}

function floatReferrer(r){

if(!r||r=='')return '&nbsp;';
var idx,sr='Unknown',R=r.split('/');
sr=R[2];

fLink++;
return '<span class=floatUser id=fLink'+fLink+' onmouseover="floatNearShow('+fLink+',\''+r+'\')">'+sr+'</span>';
}

function floatUserAgent(ua){

var idx,sua='Other';

if((idx=ua.indexOf('MSIE'))!=-1)sua=ua.substring(idx,ua.indexOf(';',idx));
else if((idx=ua.indexOf('Firefox'))!=-1)sua=ua.substring(idx);
else if((idx=ua.indexOf('BlackBerry'))!=-1)sua=ua.substring(idx,ua.indexOf(' ',idx));
else if((idx=ua.indexOf('iPhone'))!=-1)sua=ua.substring(idx,ua.indexOf(';',idx));
else if((idx=ua.indexOf('Chrome'))!=-1)sua=ua.substring(idx,ua.indexOf(' ',idx));
else if((idx=ua.indexOf('Netscape'))!=-1)sua=ua.substring(idx);
else if((idx=ua.indexOf('Lotus-Notes'))!=-1)sua=ua.substring(idx,ua.indexOf(';',idx));
else if((idx=ua.indexOf('Safari'))!=-1)sua=ua.substring(idx);

if(ua=='')ua='<i>empty</i>';

fLink++;
return '<span class=floatUser id=fLink'+fLink+' onmouseover="floatNearShow('+fLink+',\''+ua+'\')">'+sua+'</span>';
}



function contactSubmit(){
var F=gel('contactForm'),
S=gel('contactFormSpan'),
data='name='+escape(getVal('name'))
+'&email='+escape(getVal('email'))
+'&comment='+escape(getVal('comment'));

S.innerHTML='<i>Sending...</i>';
ckajax.getText('contact_sub.php',data,function(stat,statStr,resp){
S.innerHTML=resp;
if(resp.indexOf('Error:')!=-1)S.style.color='#ff0000';
else S.innerHTML='Message Sent!';
gel('name').onfocus=gel('email').onfocus=gel('comment').onfocus=function(){
gel('contactFormSpan').innerHTML=gel('comment').value='';
gel('name').onfocus=gel('email').onfocus=gel('comment').onfocus=null;
};
});
}





function loadWxp(){
debug('loadWxp()');
updateMainPage();
return wxp_ready=1;


r=ckajax.getText('webtext.txt',null,function(stat,statStr,resp){
var R=parseResponse(resp),
w=[];
for(var i in R){
if(!w[i])
w[i]=[];
for(var n in R[i])
for(var j in R[i][n])
w[i][j]=b64dec(R[i][n][j]);
}
webtext=w;

wxp_ready=1;
});
}
function loginMessage(msg){
debug('loginMessage('+msg+')');
if(!msg)
msg=loginMessage.msg;
loginMessage.msg=msg;

if(msg=='pswdsent')msg=wtext('login.pswdsent');
if(msg=='joingroup')msg=wtext('login.joingroup');
if(msg=='login')msg=wtext('login.login');
if(msg=='alreadyverified')msg=wtext('login.alreadyverified');

if(loggedIn()){
if(!wxpemail)
return setTimeout(function(){loginMessage()},250);
floatAsk('&nbsp;',wtext('login.joingroup'),
[button(wtext('close'),'fC()')]);
}else{
var M=gel('loginMsg');
if(!M)
return setTimeout(function(){loginMessage()},250);
M.style.color='#ff0000';
M.innerHTML=msg;
}

setCookie('wxploginmsg=');
}
function updateMainPage(){
var e=unescape(getCookie('wxpemail')),
E=gel('loginemail'),
T=gel('loginTable');
if(!T&&URL.indexOf('?reg')==-1&&URL.indexOf('?login')==-1)
return setTimeout(updateMainPage,1000);

if(!e)
return;

var msg=getCookie('wxploginmsg');
if(msg!='')
loginMessage(msg);

if(E&&!loggedIn()){
E.style.color='#000000';
E.style.fontStyle='normal';
E.touch=1;
E.value=e;
gel('loginpasswordx').focus();

return;
}

if(T)
T.innerHTML='<table class=loginTab style="height:132px;width:500px"><tr><td align=center valign=center>'+
iLink('gotoPage(\'reg\')','Return to Dashboard')+'<br/>'+iLink('logout()','Logout of Dashboard')+
'</td></tr></table>';
}
loadWxp();


var idx=URL.indexOf(BASEURL),
idxq=URL.indexOf('?');
if(URL.indexOf('?video')==-1)
if(idx!=0||window!=window.top||URL.indexOf('#?')!=-1){
window.top.location.href=BASEURL+URL.substr(idxq==-1?0:idxq);
}
var url2=URL.replace('//?','/?');
if(url2!=URL)
document.location.href=url2;


if(URL.indexOf('debug=on')!=-1){
document.cookie='debug=on';
DEBUG=1;
}
if(URL.indexOf('debug=off')!=-1){
document.cookie='debug=off';
DEBUG=0;
}
if(document.cookie.indexOf('debug=on')!=-1)
DEBUG=1;
debug('hostname='+HOSTNAME);


function wxpKeyPress(ev){
var kC=(window.event)?event.keyCode:ev.keyCode;
var Esc=(window.event)?27:ev.DOM_VK_ESCAPE;
if(kC==Esc)fC();
};


function deltaTime(){
if(!deltaTime.A)
deltaTime.A={n:0,last:0};
var now=utime(),
fcn=arguments.callee.caller,
sig='anonymous';

if(fcn.name){
sig=fcn.name;
}else{
var def=fcn.toString(),
name=def.substring(def.indexOf('function')+8,def.indexOf('('));
sig=name?name:'anonymous'; 
}
var delta=now-deltaTime.A.last;
deltaTime.A.last=now;
return sig+' t='+now+' delta='+delta+'.\n';
}
var debug_to=0;
function debug(msg,quiet){
if(!DEBUG)
return msg;

if(msg)
debuglog+='['+(new Date())+']['+currentTimeDelta+']'+msg+'\n';

if(quiet)
return msg;

try{
gel('debug').innerHTML='<xmp>'+debuglog+'</xmp>';

debug_to=0;
}catch(e){
if(msg&&debug_to!=0)
return msg;
debug_to=setTimeout(function(){debug()},1000);
}
return msg;
}
function debugpost(msg,stk){
xmlreq=new XMLHttpRequest();
xmlreq.open('POST','debug.php',false);
xmlreq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlreq.send('msg='+escape(msg)+'\nstk='+stk);
return msg;
}
function stackTrace(_fcn){
var fcn=arguments.callee.caller,
msg='Stack trace: <br/>\n';

if(_fcn)
fcn=_fcn;

while(fcn){

var sig,
arg=fcn.arguments;

if(fcn.name){
sig=fcn.name;
}else{
var def=fcn.toString(),
name=def.substring(def.indexOf('function')+8,def.indexOf('('));
sig=name?name:'anonymous'; 
}
sig+='(';

if(arg)for(var x=0;x<arg.length;x++){

var a=arg[x];
if(a&&a.length>300)
a=a.substring(0,300)+'...';

sig+='\''+a+'\'';

if(x <arg.length-1)
sig+=',';
}
sig+=')';


msg+='-'+sig+'<br/>\n';
fcn=fcn.caller;
}
return msg+='<br/>\n\n';
}























function CP_stop(e){if(e&&e.stopPropagation){e.stopPropagation();}}
function CalendarPopup(){var c;if(arguments.length>0){c=new PopupWindow(arguments[0]);}else{c=new PopupWindow();c.setSize(150,175);}c.offsetX=-152;c.offsetY=25;c.autoHide();c.monthNames=new Array("January","February","March","April","May","June","July","August","September","October","November","December");c.monthAbbreviations=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");c.dayHeaders=new Array("S","M","T","W","T","F","S");c.returnFunction="CP_tmpReturnFunction";c.returnMonthFunction="CP_tmpReturnMonthFunction";c.returnQuarterFunction="CP_tmpReturnQuarterFunction";c.returnYearFunction="CP_tmpReturnYearFunction";c.weekStartDay=0;c.isShowYearNavigation=false;c.displayType="date";c.disabledWeekDays=new Object();c.disabledDatesExpression="";c.yearSelectStartOffset=2;c.currentDate=null;c.todayText="Today";c.cssPrefix="";c.isShowNavigationDropdowns=false;c.isShowYearNavigationInput=false;window.CP_calendarObject=null;window.CP_targetInput=null;window.CP_dateFormat="MM/dd/yyyy";c.copyMonthNamesToWindow=CP_copyMonthNamesToWindow;c.setReturnFunction=CP_setReturnFunction;c.setReturnMonthFunction=CP_setReturnMonthFunction;c.setReturnQuarterFunction=CP_setReturnQuarterFunction;c.setReturnYearFunction=CP_setReturnYearFunction;c.setMonthNames=CP_setMonthNames;c.setMonthAbbreviations=CP_setMonthAbbreviations;c.setDayHeaders=CP_setDayHeaders;c.setWeekStartDay=CP_setWeekStartDay;c.setDisplayType=CP_setDisplayType;c.setDisabledWeekDays=CP_setDisabledWeekDays;c.addDisabledDates=CP_addDisabledDates;c.setYearSelectStartOffset=CP_setYearSelectStartOffset;c.setTodayText=CP_setTodayText;c.showYearNavigation=CP_showYearNavigation;c.showCalendar=CP_showCalendar;c.hideCalendar=CP_hideCalendar;c.getStyles=getCalendarStyles;c.refreshCalendar=CP_refreshCalendar;c.getCalendar=CP_getCalendar;c.select=CP_select;c.setCssPrefix=CP_setCssPrefix;c.showNavigationDropdowns=CP_showNavigationDropdowns;c.showYearNavigationInput=CP_showYearNavigationInput;c.copyMonthNamesToWindow();return c;}
function CP_copyMonthNamesToWindow(){if(typeof(window.MONTH_NAMES)!="undefined"&&window.MONTH_NAMES!=null){window.MONTH_NAMES=new Array();for(var i=0;i<this.monthNames.length;i++){window.MONTH_NAMES[window.MONTH_NAMES.length]=this.monthNames[i];}for(var i=0;i<this.monthAbbreviations.length;i++){window.MONTH_NAMES[window.MONTH_NAMES.length]=this.monthAbbreviations[i];}}}
function CP_tmpReturnFunction(y,m,d){if(window.CP_targetInput!=null){var dt=new Date(y,m-1,d,0,0,0);if(window.CP_calendarObject!=null){window.CP_calendarObject.copyMonthNamesToWindow();}window.CP_targetInput.value=formatDate(dt,window.CP_dateFormat);}else{alert('Use setReturnFunction()to define which function will get the clicked results!');}}
function CP_tmpReturnMonthFunction(y,m){alert('Use setReturnMonthFunction()to define which function will get the clicked results!\nYou clicked: year='+y+',month='+m);}
function CP_tmpReturnQuarterFunction(y,q){alert('Use setReturnQuarterFunction()to define which function will get the clicked results!\nYou clicked: year='+y+',quarter='+q);}
function CP_tmpReturnYearFunction(y){alert('Use setReturnYearFunction()to define which function will get the clicked results!\nYou clicked: year='+y);}
function CP_setReturnFunction(name){this.returnFunction=name;}
function CP_setReturnMonthFunction(name){this.returnMonthFunction=name;}
function CP_setReturnQuarterFunction(name){this.returnQuarterFunction=name;}
function CP_setReturnYearFunction(name){this.returnYearFunction=name;}
function CP_setMonthNames(){for(var i=0;i<arguments.length;i++){this.monthNames[i]=arguments[i];}this.copyMonthNamesToWindow();}
function CP_setMonthAbbreviations(){for(var i=0;i<arguments.length;i++){this.monthAbbreviations[i]=arguments[i];}this.copyMonthNamesToWindow();}
function CP_setDayHeaders(){for(var i=0;i<arguments.length;i++){this.dayHeaders[i]=arguments[i];}}
function CP_setWeekStartDay(day){this.weekStartDay=day;}
function CP_showYearNavigation(){this.isShowYearNavigation=(arguments.length>0)?arguments[0]:true;}
function CP_setDisplayType(type){if(type!="date"&&type!="week-end"&&type!="month"&&type!="quarter"&&type!="year"){alert("Invalid display type! Must be one of: date,week-end,month,quarter,year");return false;}this.displayType=type;}
function CP_setYearSelectStartOffset(num){this.yearSelectStartOffset=num;}
function CP_setDisabledWeekDays(){this.disabledWeekDays=new Object();for(var i=0;i<arguments.length;i++){this.disabledWeekDays[arguments[i]]=true;}}
function CP_addDisabledDates(start,end){if(arguments.length==1){end=start;}if(start==null&&end==null){return;}if(this.disabledDatesExpression!=""){this.disabledDatesExpression+="||";}if(start!=null){start=parseDate(start);start=""+start.getFullYear()+LZ(start.getMonth()+1)+LZ(start.getDate());}if(end!=null){end=parseDate(end);end=""+end.getFullYear()+LZ(end.getMonth()+1)+LZ(end.getDate());}if(start==null){this.disabledDatesExpression+="(ds<="+end+")";}else if(end==null){this.disabledDatesExpression+="(ds>="+start+")";}else{this.disabledDatesExpression+="(ds>="+start+"&&ds<="+end+")";}}
function CP_setTodayText(text){this.todayText=text;}
function CP_setCssPrefix(val){this.cssPrefix=val;}
function CP_showNavigationDropdowns(){this.isShowNavigationDropdowns=(arguments.length>0)?arguments[0]:true;}
function CP_showYearNavigationInput(){this.isShowYearNavigationInput=(arguments.length>0)?arguments[0]:true;}
function CP_hideCalendar(){if(arguments.length>0){window.popupWindowObjects[arguments[0]].hidePopup();}else{this.hidePopup();}}
function CP_refreshCalendar(index){var calObject=window.popupWindowObjects[index];if(arguments.length>1){calObject.populate(calObject.getCalendar(arguments[1],arguments[2],arguments[3],arguments[4],arguments[5]));}else{calObject.populate(calObject.getCalendar());}calObject.refresh();}
function CP_showCalendar(anchorname){if(arguments.length>1){if(arguments[1]==null||arguments[1]==""){this.currentDate=new Date();}else{this.currentDate=new Date(parseDate(arguments[1]));}}this.populate(this.getCalendar());this.showPopup(anchorname);}
function CP_select(inputobj,linkname,format){var selectedDate=(arguments.length>3)?arguments[3]:null;if(!window.getDateFromFormat){alert("calendar.select: To use this method you must also include 'date.js' for date formatting");return;}if(this.displayType!="date"&&this.displayType!="week-end"){alert("calendar.select: This function can only be used with displayType 'date' or 'week-end'");return;}if(inputobj.type!="text"&&inputobj.type!="hidden"&&inputobj.type!="textarea"){alert("calendar.select: Input object passed is not a valid form input object");window.CP_targetInput=null;return;}if(inputobj.disabled){return;}window.CP_targetInput=inputobj;window.CP_calendarObject=this;this.currentDate=null;var time=0;if(selectedDate!=null){time=getDateFromFormat(selectedDate,format)}else if(inputobj.value!=""){time=getDateFromFormat(inputobj.value,format);}if(selectedDate!=null||inputobj.value!=""){if(time==0){this.currentDate=null;}else{this.currentDate=new Date(time);}}window.CP_dateFormat=format;this.showCalendar(linkname);}
function getCalendarStyles(){var result="";var p="";if(this!=null&&typeof(this.cssPrefix)!="undefined"&&this.cssPrefix!=null&&this.cssPrefix!=""){p=this.cssPrefix;}result+="<STYLE>\n";result+="."+p+"cpYearNavigation,."+p+"cpMonthNavigation{background-color:#C0C0C0;text-align:center;vertical-align:center;text-decoration:none;color:#000000;font-weight:bold;}\n";result+="."+p+"cpDayColumnHeader,."+p+"cpYearNavigation,."+p+"cpMonthNavigation,."+p+"cpCurrentMonthDate,."+p+"cpCurrentMonthDateDisabled,."+p+"cpOtherMonthDate,."+p+"cpOtherMonthDateDisabled,."+p+"cpCurrentDate,."+p+"cpCurrentDateDisabled,."+p+"cpTodayText,."+p+"cpTodayTextDisabled,."+p+"cpText{font-family:arial;font-size:8pt;}\n";result+="TD."+p+"cpDayColumnHeader{text-align:right;border:solid thin #C0C0C0;border-width:0px 0px 1px 0px;}\n";result+="."+p+"cpCurrentMonthDate,."+p+"cpOtherMonthDate,."+p+"cpCurrentDate{text-align:right;text-decoration:none;}\n";result+="."+p+"cpCurrentMonthDateDisabled,."+p+"cpOtherMonthDateDisabled,."+p+"cpCurrentDateDisabled{color:#D0D0D0;text-align:right;text-decoration:line-through;}\n";result+="."+p+"cpCurrentMonthDate,.cpCurrentDate{color:#000000;}\n";result+="."+p+"cpOtherMonthDate{color:#808080;}\n";result+="TD."+p+"cpCurrentDate{color:white;background-color: #C0C0C0;border-width:1px;border:solid thin #800000;}\n";result+="TD."+p+"cpCurrentDateDisabled{border-width:1px;border:solid thin #FFAAAA;}\n";result+="TD."+p+"cpTodayText,TD."+p+"cpTodayTextDisabled{border:solid thin #C0C0C0;border-width:1px 0px 0px 0px;}\n";result+="A."+p+"cpTodayText,SPAN."+p+"cpTodayTextDisabled{height:20px;}\n";result+="A."+p+"cpTodayText{color:black;}\n";result+="."+p+"cpTodayTextDisabled{color:#D0D0D0;}\n";result+="."+p+"cpBorder{border:solid thin #808080;}\n";result+="</STYLE>\n";return result;}
function CP_getCalendar(){var now=new Date();if(this.type=="WINDOW"){var windowref="window.opener.";}else{var windowref="";}var result="";if(this.type=="WINDOW"){result+="<HTML><HEAD><TITLE>Calendar</TITLE>"+this.getStyles()+"</HEAD><BODY MARGINWIDTH=0 MARGINHEIGHT=0 TOPMARGIN=0 RIGHTMARGIN=0 LEFTMARGIN=0>\n";result+='<CENTER><TABLE WIDTH=100%BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>\n';}else{result+='<TABLE CLASS="'+this.cssPrefix+'cpBorder" WIDTH=144 BORDER=1 BORDERWIDTH=1 CELLSPACING=0 CELLPADDING=1>\n';result+='<TR><TD ALIGN=CENTER>\n';result+='<CENTER>\n';}if(this.displayType=="date"||this.displayType=="week-end"){if(this.currentDate==null){this.currentDate=now;}if(arguments.length>0){var month=arguments[0];}else{var month=this.currentDate.getMonth()+1;}if(arguments.length>1&&arguments[1]>0&&arguments[1]-0==arguments[1]){var year=arguments[1];}else{var year=this.currentDate.getFullYear();}var daysinmonth=new Array(0,31,28,31,30,31,30,31,31,30,31,30,31);if(((year%4==0)&&(year%100!=0))||(year%400==0)){daysinmonth[2]=29;}var current_month=new Date(year,month-1,1);var display_year=year;var display_month=month;var display_date=1;var weekday=current_month.getDay();var offset=0;offset=(weekday>=this.weekStartDay)?weekday-this.weekStartDay:7-this.weekStartDay+weekday;if(offset>0){display_month--;if(display_month <1){display_month=12;display_year--;}display_date=daysinmonth[display_month]-offset+1;}var next_month=month+1;var next_month_year=year;if(next_month>12){next_month=1;next_month_year++;}var last_month=month-1;var last_month_year=year;if(last_month <1){last_month=12;last_month_year--;}var date_class;if(this.type!="WINDOW"){result+="<TABLE WIDTH=144 BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>";}result+='<TR>\n';var refresh=windowref+'CP_refreshCalendar';var refreshLink='javascript:'+refresh;if(this.isShowNavigationDropdowns){result+='<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="78" COLSPAN="3"><select CLASS="'+this.cssPrefix+'cpMonthNavigation" name="cpMonth" onmouseup="CP_stop(event)" onChange="'+refresh+'('+this.index+',this.options[this.selectedIndex].value-0,'+(year-0)+');">';for(var monthCounter=1;monthCounter<=12;monthCounter++){var selected=(monthCounter==month)?'SELECTED':'';result+='<option value="'+monthCounter+'" '+selected+'>'+this.monthNames[monthCounter-1]+'</option>';}result+='</select></TD>';result+='<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10">&nbsp;</TD>';result+='<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="56" COLSPAN="3"><select CLASS="'+this.cssPrefix+'cpYearNavigation" name="cpYear" onmouseup="CP_stop(event)" onChange="'+refresh+'('+this.index+','+month+',this.options[this.selectedIndex].value-0);">';for(var yearCounter=year-this.yearSelectStartOffset;yearCounter<=year+this.yearSelectStartOffset;yearCounter++){var selected=(yearCounter==year)?'SELECTED':'';result+='<option value="'+yearCounter+'" '+selected+'>'+yearCounter+'</option>';}result+='</select></TD>';}else{if(this.isShowYearNavigation){result+='<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpMonthNavigation" HREF="'+refreshLink+'('+this.index+','+last_month+','+last_month_year+');">&lt;</A></TD>';result+='<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="58"><SPAN CLASS="'+this.cssPrefix+'cpMonthNavigation">'+this.monthNames[month-1]+'</SPAN></TD>';result+='<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpMonthNavigation" HREF="'+refreshLink+'('+this.index+','+next_month+','+next_month_year+');">&gt;</A></TD>';result+='<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10">&nbsp;</TD>';result+='<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="'+refreshLink+'('+this.index+','+month+','+(year-1)+');">&lt;</A></TD>';if(this.isShowYearNavigationInput){result+='<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="36"><INPUT NAME="cpYear" CLASS="'+this.cssPrefix+'cpYearNavigation" SIZE="4" MAXLENGTH="4" VALUE="'+year+'" onBlur="'+refresh+'('+this.index+','+month+',this.value-0);"></TD>';}else{result+='<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="36"><SPAN CLASS="'+this.cssPrefix+'cpYearNavigation">'+year+'</SPAN></TD>';}result+='<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="'+refreshLink+'('+this.index+','+month+','+(year+1)+');">&gt;</A></TD>';}else{result+='<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="22"><A CLASS="'+this.cssPrefix+'cpMonthNavigation" HREF="'+refreshLink+'('+this.index+','+last_month+','+last_month_year+');">&lt;&lt;</A></TD>\n';result+='<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="100"><SPAN CLASS="'+this.cssPrefix+'cpMonthNavigation">'+this.monthNames[month-1]+' '+year+'</SPAN></TD>\n';result+='<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="22"><A CLASS="'+this.cssPrefix+'cpMonthNavigation" HREF="'+refreshLink+'('+this.index+','+next_month+','+next_month_year+');">&gt;&gt;</A></TD>\n';}}result+='</TR></TABLE>\n';result+='<TABLE WIDTH=120 BORDER=0 CELLSPACING=0 CELLPADDING=1 ALIGN=CENTER>\n';result+='<TR>\n';for(var j=0;j<7;j++){result+='<TD CLASS="'+this.cssPrefix+'cpDayColumnHeader" WIDTH="14%"><SPAN CLASS="'+this.cssPrefix+'cpDayColumnHeader">'+this.dayHeaders[(this.weekStartDay+j)%7]+'</TD>\n';}result+='</TR>\n';for(var row=1;row<=6;row++){result+='<TR>\n';for(var col=1;col<=7;col++){var disabled=false;if(this.disabledDatesExpression!=""){var ds=""+display_year+LZ(display_month)+LZ(display_date);eval("disabled=("+this.disabledDatesExpression+")");}var dateClass="";if((display_month==this.currentDate.getMonth()+1)&&(display_date==this.currentDate.getDate())&&(display_year==this.currentDate.getFullYear())){dateClass="cpCurrentDate";}else if(display_month==month){dateClass="cpCurrentMonthDate";}else{dateClass="cpOtherMonthDate";}if(disabled||this.disabledWeekDays[col-1]){result+='	<TD CLASS="'+this.cssPrefix+dateClass+'"><SPAN CLASS="'+this.cssPrefix+dateClass+'Disabled">'+display_date+'</SPAN></TD>\n';}else{var selected_date=display_date;var selected_month=display_month;var selected_year=display_year;if(this.displayType=="week-end"){var d=new Date(selected_year,selected_month-1,selected_date,0,0,0,0);d.setDate(d.getDate()+(7-col));selected_year=d.getYear();if(selected_year <1000){selected_year+=1900;}selected_month=d.getMonth()+1;selected_date=d.getDate();}result+='	<TD CLASS="'+this.cssPrefix+dateClass+'"><A HREF="javascript:'+windowref+this.returnFunction+'('+selected_year+','+selected_month+','+selected_date+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+this.cssPrefix+dateClass+'">'+display_date+'</A></TD>\n';}display_date++;if(display_date>daysinmonth[display_month]){display_date=1;display_month++;}if(display_month>12){display_month=1;display_year++;}}result+='</TR>';}var current_weekday=now.getDay()-this.weekStartDay;if(current_weekday <0){current_weekday+=7;}result+='<TR>\n';result+='	<TD COLSPAN=7 ALIGN=CENTER CLASS="'+this.cssPrefix+'cpTodayText">\n';if(this.disabledDatesExpression!=""){var ds=""+now.getFullYear()+LZ(now.getMonth()+1)+LZ(now.getDate());eval("disabled=("+this.disabledDatesExpression+")");}if(disabled||this.disabledWeekDays[current_weekday+1]){result+='		<SPAN CLASS="'+this.cssPrefix+'cpTodayTextDisabled">'+this.todayText+'</SPAN>\n';}else{result+='		<A CLASS="'+this.cssPrefix+'cpTodayText" HREF="javascript:'+windowref+this.returnFunction+'(\''+now.getFullYear()+'\',\''+(now.getMonth()+1)+'\',\''+now.getDate()+'\');'+windowref+'CP_hideCalendar(\''+this.index+'\');">'+this.todayText+'</A>\n';}result+='		<BR>\n';result+='	</TD></TR></TABLE></CENTER></TD></TR></TABLE>\n';}if(this.displayType=="month"||this.displayType=="quarter"||this.displayType=="year"){if(arguments.length>0){var year=arguments[0];}else{if(this.displayType=="year"){var year=now.getFullYear()-this.yearSelectStartOffset;}else{var year=now.getFullYear();}}if(this.displayType!="year"&&this.isShowYearNavigation){result+="<TABLE WIDTH=144 BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>";result+='<TR>\n';result+='	<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="22"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year-1)+');">&lt;&lt;</A></TD>\n';result+='	<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="100">'+year+'</TD>\n';result+='	<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="22"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year+1)+');">&gt;&gt;</A></TD>\n';result+='</TR></TABLE>\n';}}if(this.displayType=="month"){result+='<TABLE WIDTH=120 BORDER=0 CELLSPACING=1 CELLPADDING=0 ALIGN=CENTER>\n';for(var i=0;i<4;i++){result+='<TR>';for(var j=0;j<3;j++){var monthindex=((i*3)+j);result+='<TD WIDTH=33%ALIGN=CENTER><A CLASS="'+this.cssPrefix+'cpText" HREF="javascript:'+windowref+this.returnMonthFunction+'('+year+','+(monthindex+1)+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">'+this.monthAbbreviations[monthindex]+'</A></TD>';}result+='</TR>';}result+='</TABLE></CENTER></TD></TR></TABLE>\n';}if(this.displayType=="quarter"){result+='<BR><TABLE WIDTH=120 BORDER=1 CELLSPACING=0 CELLPADDING=0 ALIGN=CENTER>\n';for(var i=0;i<2;i++){result+='<TR>';for(var j=0;j<2;j++){var quarter=((i*2)+j+1);result+='<TD WIDTH=50%ALIGN=CENTER><BR><A CLASS="'+this.cssPrefix+'cpText" HREF="javascript:'+windowref+this.returnQuarterFunction+'('+year+','+quarter+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">Q'+quarter+'</A><BR><BR></TD>';}result+='</TR>';}result+='</TABLE></CENTER></TD></TR></TABLE>\n';}if(this.displayType=="year"){var yearColumnSize=4;result+="<TABLE WIDTH=144 BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>";result+='<TR>\n';result+='	<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="50%"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year-(yearColumnSize*2))+');">&lt;&lt;</A></TD>\n';result+='	<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="50%"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year+(yearColumnSize*2))+');">&gt;&gt;</A></TD>\n';result+='</TR></TABLE>\n';result+='<TABLE WIDTH=120 BORDER=0 CELLSPACING=1 CELLPADDING=0 ALIGN=CENTER>\n';for(var i=0;i<yearColumnSize;i++){for(var j=0;j<2;j++){var currentyear=year+(j*yearColumnSize)+i;result+='<TD WIDTH=50%ALIGN=CENTER><A CLASS="'+this.cssPrefix+'cpText" HREF="javascript:'+windowref+this.returnYearFunction+'('+currentyear+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">'+currentyear+'</A></TD>';}result+='</TR>';}result+='</TABLE></CENTER></TD></TR></TABLE>\n';}if(this.type=="WINDOW"){result+="</BODY></HTML>\n";}return result;}





















function getAnchorPosition(anchorname){var useWindow=false;var coordinates=new Object();var x=0,y=0;var use_gebi=false,use_css=false,use_layers=false;if(document.getElementById){use_gebi=true;}else if(document.all){use_css=true;}else if(document.layers){use_layers=true;}if(use_gebi&&document.all){x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);}else if(use_gebi){var o=document.getElementById(anchorname);x=AnchorPosition_getPageOffsetLeft(o);y=AnchorPosition_getPageOffsetTop(o);}else if(use_css){x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);}else if(use_layers){var found=0;for(var i=0;i<document.anchors.length;i++){if(document.anchors[i].name==anchorname){found=1;break;}}if(found==0){coordinates.x=0;coordinates.y=0;return coordinates;}x=document.anchors[i].x;y=document.anchors[i].y;}else{coordinates.x=0;coordinates.y=0;return coordinates;}coordinates.x=x;coordinates.y=y;return coordinates;}
function getAnchorWindowPosition(anchorname){var coordinates=getAnchorPosition(anchorname);var x=0;var y=0;if(document.getElementById){if(isNaN(window.screenX)){x=coordinates.x-document.body.scrollLeft+window.screenLeft;y=coordinates.y-document.body.scrollTop+window.screenTop;}else{x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;}}else if(document.all){x=coordinates.x-document.body.scrollLeft+window.screenLeft;y=coordinates.y-document.body.scrollTop+window.screenTop;}else if(document.layers){x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;}coordinates.x=x;coordinates.y=y;return coordinates;}
function AnchorPosition_getPageOffsetLeft(el){var ol=el.offsetLeft;while((el=el.offsetParent)!=null){ol+=el.offsetLeft;}return ol;}
function AnchorPosition_getWindowOffsetLeft(el){return AnchorPosition_getPageOffsetLeft(el)-document.body.scrollLeft;}
function AnchorPosition_getPageOffsetTop(el){var ot=el.offsetTop;while((el=el.offsetParent)!=null){ot+=el.offsetTop;}return ot;}
function AnchorPosition_getWindowOffsetTop(el){return AnchorPosition_getPageOffsetTop(el)-document.body.scrollTop;}





















var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x){return(x<0||x>9?"":"0")+x}
function isDate(val,format){var date=getDateFromFormat(val,format);if(date==0){return false;}return true;}
function compareDates(date1,dateformat1,date2,dateformat2){var d1=getDateFromFormat(date1,dateformat1);var d2=getDateFromFormat(date2,dateformat2);if(d1==0||d2==0){return-1;}else if(d1>d2){return 1;}return 0;}
function formatDate(date,format){format=format+"";var result="";var i_format=0;var c="";var token="";var y=date.getYear()+"";var M=date.getMonth()+1;var d=date.getDate();var E=date.getDay();var H=date.getHours();var m=date.getMinutes();var s=date.getSeconds();var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;var value=new Object();if(y.length <4){y=""+(y-0+1900);}value["y"]=""+y;value["yyyy"]=y;value["yy"]=y.substring(2,4);value["M"]=M;value["MM"]=LZ(M);value["MMM"]=MONTH_NAMES[M-1];value["NNN"]=MONTH_NAMES[M+11];value["d"]=d;value["dd"]=LZ(d);value["E"]=DAY_NAMES[E+7];value["EE"]=DAY_NAMES[E];value["H"]=H;value["HH"]=LZ(H);if(H==0){value["h"]=12;}else if(H>12){value["h"]=H-12;}else{value["h"]=H;}value["hh"]=LZ(value["h"]);if(H>11){value["K"]=H-12;}else{value["K"]=H;}value["k"]=H+1;value["KK"]=LZ(value["K"]);value["kk"]=LZ(value["k"]);if(H>11){value["a"]="PM";}else{value["a"]="AM";}value["m"]=m;value["mm"]=LZ(m);value["s"]=s;value["ss"]=LZ(s);while(i_format <format.length){c=format.charAt(i_format);token="";while((format.charAt(i_format)==c)&&(i_format <format.length)){token+=format.charAt(i_format++);}if(value[token]!=null){result=result+value[token];}else{result=result+token;}}return result;}
function _isInteger(val){var digits="1234567890";for(var i=0;i <val.length;i++){if(digits.indexOf(val.charAt(i))==-1){return false;}}return true;}
function _getInt(str,i,minlength,maxlength){for(var x=maxlength;x>=minlength;x--){var token=str.substring(i,i+x);if(token.length <minlength){return null;}if(_isInteger(token)){return token;}}return null;}
function getDateFromFormat(val,format){val=val+"";format=format+"";var i_val=0;var i_format=0;var c="";var token="";var token2="";var x,y;var now=new Date();var year=now.getYear();var month=now.getMonth()+1;var date=1;var hh=now.getHours();var mm=now.getMinutes();var ss=now.getSeconds();var ampm="";while(i_format <format.length){c=format.charAt(i_format);token="";while((format.charAt(i_format)==c)&&(i_format <format.length)){token+=format.charAt(i_format++);}if(token=="yyyy"||token=="yy"||token=="y"){if(token=="yyyy"){x=4;y=4;}if(token=="yy"){x=2;y=2;}if(token=="y"){x=2;y=4;}year=_getInt(val,i_val,x,y);if(year==null){return 0;}i_val+=year.length;if(year.length==2){if(year>70){year=1900+(year-0);}else{year=2000+(year-0);}}}else if(token=="MMM"||token=="NNN"){month=0;for(var i=0;i<MONTH_NAMES.length;i++){var month_name=MONTH_NAMES[i];if(val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()){if(token=="MMM"||(token=="NNN"&&i>11)){month=i+1;if(month>12){month-=12;}i_val+=month_name.length;break;}}}if((month <1)||(month>12)){return 0;}}else if(token=="EE"||token=="E"){for(var i=0;i<DAY_NAMES.length;i++){var day_name=DAY_NAMES[i];if(val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()){i_val+=day_name.length;break;}}}else if(token=="MM"||token=="M"){month=_getInt(val,i_val,token.length,2);if(month==null||(month<1)||(month>12)){return 0;}i_val+=month.length;}else if(token=="dd"||token=="d"){date=_getInt(val,i_val,token.length,2);if(date==null||(date<1)||(date>31)){return 0;}i_val+=date.length;}else if(token=="hh"||token=="h"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<1)||(hh>12)){return 0;}i_val+=hh.length;}else if(token=="HH"||token=="H"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<0)||(hh>23)){return 0;}i_val+=hh.length;}else if(token=="KK"||token=="K"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<0)||(hh>11)){return 0;}i_val+=hh.length;}else if(token=="kk"||token=="k"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<1)||(hh>24)){return 0;}i_val+=hh.length;hh--;}else if(token=="mm"||token=="m"){mm=_getInt(val,i_val,token.length,2);if(mm==null||(mm<0)||(mm>59)){return 0;}i_val+=mm.length;}else if(token=="ss"||token=="s"){ss=_getInt(val,i_val,token.length,2);if(ss==null||(ss<0)||(ss>59)){return 0;}i_val+=ss.length;}else if(token=="a"){if(val.substring(i_val,i_val+2).toLowerCase()=="am"){ampm="AM";}else if(val.substring(i_val,i_val+2).toLowerCase()=="pm"){ampm="PM";}else{return 0;}i_val+=2;}else{if(val.substring(i_val,i_val+token.length)!=token){return 0;}else{i_val+=token.length;}}}if(i_val!=val.length){return 0;}if(month==2){if(((year%4==0)&&(year%100!=0))||(year%400==0)){if(date>29){return 0;}}else{if(date>28){return 0;}}}if((month==4)||(month==6)||(month==9)||(month==11)){if(date>30){return 0;}}if(hh<12&&ampm=="PM"){hh=hh-0+12;}else if(hh>11&&ampm=="AM"){hh-=12;}var newdate=new Date(year,month-1,date,hh,mm,ss);return newdate.getTime();}
function parseDate(val){var preferEuro=(arguments.length==2)?arguments[1]:false;generalFormats=new Array('y-M-d','MMM d,y','MMM d,y','y-MMM-d','d-MMM-y','MMM d');monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','MMM dd yyyy','M/d','M-d');dateFirst=new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M');var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');var d=null;for(var i=0;i<checkList.length;i++){var l=window[checkList[i]];for(var j=0;j<l.length;j++){d=getDateFromFormat(val,l[j]);if(d!=0){return new Date(d);}}}return null;}





















function PopupWindow_getXYPosition(anchorname){var coordinates;if(this.type=="WINDOW"){coordinates=getAnchorWindowPosition(anchorname);}else{coordinates=getAnchorPosition(anchorname);}this.x=coordinates.x;this.y=coordinates.y;}
function PopupWindow_setSize(width,height){this.width=width;this.height=height;}
function PopupWindow_populate(contents){this.contents=contents;this.populated=false;}
function PopupWindow_setUrl(url){this.url=url;}
function PopupWindow_setWindowProperties(props){this.windowProperties=props;}
function PopupWindow_refresh(){if(this.divName!=null){if(this.use_gebi){document.getElementById(this.divName).innerHTML=this.contents;}else if(this.use_css){document.all[this.divName].innerHTML=this.contents;}else if(this.use_layers){var d=document.layers[this.divName];d.document.open();d.document.writeln(this.contents);d.document.close();}}else{if(this.popupWindow!=null&&!this.popupWindow.closed){if(this.url!=""){this.popupWindow.location.href=this.url;}else{this.popupWindow.document.open();this.popupWindow.document.writeln(this.contents);this.popupWindow.document.close();}this.popupWindow.focus();}}}
function PopupWindow_showPopup(anchorname){this.getXYPosition(anchorname);this.x+=this.offsetX;this.y+=this.offsetY;if(!this.populated&&(this.contents!="")){this.populated=true;this.refresh();}if(this.divName!=null){if(this.use_gebi){document.getElementById(this.divName).style.left=this.x+"px";document.getElementById(this.divName).style.top=this.y+"px";document.getElementById(this.divName).style.visibility="visible";}else if(this.use_css){document.all[this.divName].style.left=this.x;document.all[this.divName].style.top=this.y;document.all[this.divName].style.visibility="visible";}else if(this.use_layers){document.layers[this.divName].left=this.x;document.layers[this.divName].top=this.y;document.layers[this.divName].visibility="visible";}}else{if(this.popupWindow==null||this.popupWindow.closed){if(this.x<0){this.x=0;}if(this.y<0){this.y=0;}if(screen&&screen.availHeight){if((this.y+this.height)>screen.availHeight){this.y=screen.availHeight-this.height;}}if(screen&&screen.availWidth){if((this.x+this.width)>screen.availWidth){this.x=screen.availWidth-this.width;}}var avoidAboutBlank=window.opera||(document.layers&&!navigator.mimeTypes['*'])||navigator.vendor=='KDE'||(document.childNodes&&!document.all&&!navigator.taintEnabled);this.popupWindow=window.open(avoidAboutBlank?"":"about:blank","window_"+anchorname,this.windowProperties+",width="+this.width+",height="+this.height+",screenX="+this.x+",left="+this.x+",screenY="+this.y+",top="+this.y+"");}this.refresh();}}
function PopupWindow_hidePopup(){if(this.divName!=null){if(this.use_gebi){document.getElementById(this.divName).style.visibility="hidden";}else if(this.use_css){document.all[this.divName].style.visibility="hidden";}else if(this.use_layers){document.layers[this.divName].visibility="hidden";}}else{if(this.popupWindow&&!this.popupWindow.closed){this.popupWindow.close();this.popupWindow=null;}}}
function PopupWindow_isClicked(e){if(this.divName!=null){if(this.use_layers){var clickX=e.pageX;var clickY=e.pageY;var t=document.layers[this.divName];if((clickX>t.left)&&(clickX <t.left+t.clip.width)&&(clickY>t.top)&&(clickY <t.top+t.clip.height)){return true;}else{return false;}}else if(document.all){var t=window.event.srcElement;while(t.parentElement!=null){if(t.id==this.divName){return true;}t=t.parentElement;}return false;}else if(this.use_gebi&&e){var t=e.originalTarget;
try{
while(t.parentNode!=null){if(t.id==this.divName){return true;}t=t.parentNode;}
}catch(ee){}
return false;}return false;}return false;}
function PopupWindow_hideIfNotClicked(e){if(this.autoHideEnabled&&!this.isClicked(e)){this.hidePopup();}}
function PopupWindow_autoHide(){this.autoHideEnabled=true;}
function PopupWindow_hidePopupWindows(e){for(var i=0;i<popupWindowObjects.length;i++){if(popupWindowObjects[i]!=null){var p=popupWindowObjects[i];p.hideIfNotClicked(e);}}}
function PopupWindow_attachListener(){if(document.layers){document.captureEvents(Event.MOUSEUP);}window.popupWindowOldEventListener=document.onmouseup;if(window.popupWindowOldEventListener!=null){document.onmouseup=new Function("window.popupWindowOldEventListener();PopupWindow_hidePopupWindows();");}else{document.onmouseup=PopupWindow_hidePopupWindows;}}
function PopupWindow(){if(!window.popupWindowIndex){window.popupWindowIndex=0;}if(!window.popupWindowObjects){window.popupWindowObjects=new Array();}if(!window.listenerAttached){window.listenerAttached=true;PopupWindow_attachListener();}this.index=popupWindowIndex++;popupWindowObjects[this.index]=this;this.divName=null;this.popupWindow=null;this.width=0;this.height=0;this.populated=false;this.visible=false;this.autoHideEnabled=false;this.contents="";this.url="";this.windowProperties="toolbar=no,location=no,status=no,menubar=no,scrollbars=auto,resizable,alwaysRaised,dependent,titlebar=no";if(arguments.length>0){this.type="DIV";this.divName=arguments[0];}else{this.type="WINDOW";}this.use_gebi=false;this.use_css=false;this.use_layers=false;if(document.getElementById){this.use_gebi=true;}else if(document.all){this.use_css=true;}else if(document.layers){this.use_layers=true;}else{this.type="WINDOW";}this.offsetX=0;this.offsetY=0;this.getXYPosition=PopupWindow_getXYPosition;this.populate=PopupWindow_populate;this.setUrl=PopupWindow_setUrl;this.setWindowProperties=PopupWindow_setWindowProperties;this.refresh=PopupWindow_refresh;this.showPopup=PopupWindow_showPopup;this.hidePopup=PopupWindow_hidePopup;this.setSize=PopupWindow_setSize;this.isClicked=PopupWindow_isClicked;this.autoHide=PopupWindow_autoHide;this.hideIfNotClicked=PopupWindow_hideIfNotClicked;}
































window.CoolClock=function(canvasId,displayRadius,skinId,showSecondHand,gmtOffset){
return this.init(canvasId,displayRadius,skinId,showSecondHand,gmtOffset);
}

CoolClock.findAndCreateClocksArr=function(C){
for(var i=0;i<C.length;i++){
var F=C[i].className.split(" ")[0].split(":");
if(F[0]=="CoolClock"){
new CoolClock(C[i].id,F[2],F[1],F[3]!="noSeconds",F[4]);
}
}
}
CoolClock.findAndCreateClocks=function(){
var canvases=document.getElementsByTagName("canvas");
CoolClock.findAndCreateClocksArr(canvases);
}






CoolClock.addLoadEvent=function(func){
var oldonload=window.onload;
if(typeof window.onload!='function')
window.onload=func;
else
window.onload=function(){
oldonload();
func();
}
}

CoolClock.config={
clockTracker:{},
tickDelay:1000,
longTickDelay:15000,
defaultRadius:85,
renderRadius:100,
defaultSkin:"swissRail",
skins:	{



swissRail:{
outerBorder:{lineWidth:1,radius:95,color:"black",alpha:1},
smallIndicator:{lineWidth:2,startAt:89,endAt:93,color:"black",alpha:1},
largeIndicator:{lineWidth:4,startAt:80,endAt:93,color:"black",alpha:1},
hourHand:{lineWidth:8,startAt:-15,endAt:50,color:"black",alpha:1},
minuteHand:{lineWidth:7,startAt:-15,endAt:75,color:"black",alpha:1},
secondHand:{lineWidth:1,startAt:-20,endAt:85,color:"red",alpha:1},
secondDecoration:{lineWidth:1,startAt:70,radius:4,fillColor:"red",color:"red",alpha:1}
},
chunkySwiss:{
outerBorder:{lineWidth:4,radius:97,color:"black",alpha:1},
smallIndicator:{lineWidth:4,startAt:89,endAt:93,color:"black",alpha:1},
largeIndicator:{lineWidth:8,startAt:80,endAt:93,color:"black",alpha:1},
hourHand:{lineWidth:12,startAt:-15,endAt:60,color:"black",alpha:1},
minuteHand:{lineWidth:10,startAt:-15,endAt:85,color:"black",alpha:1},
secondHand:{lineWidth:4,startAt:-20,endAt:85,color:"red",alpha:1},
secondDecoration:{lineWidth:2,startAt:70,radius:8,fillColor:"red",color:"red",alpha:1}
},
chunkySwissOnBlack:{
outerBorder:{lineWidth:4,radius:97,color:"white",alpha:1},
smallIndicator:{lineWidth:4,startAt:89,endAt:93,color:"white",alpha:1},
largeIndicator:{lineWidth:8,startAt:80,endAt:93,color:"white",alpha:1},
hourHand:{lineWidth:12,startAt:-15,endAt:60,color:"white",alpha:1},
minuteHand:{lineWidth:10,startAt:-15,endAt:85,color:"white",alpha:1},
secondHand:{lineWidth:4,startAt:-20,endAt:85,color:"red",alpha:1},
secondDecoration:{lineWidth:2,startAt:70,radius:8,fillColor:"red",color:"red",alpha:1}
}

}
};

CoolClock.prototype={
init:function(canvasId,displayRadius,skinId,showSecondHand,gmtOffset){
this.canvasId=canvasId;
this.displayRadius=displayRadius||CoolClock.config.defaultRadius;
this.skinId=skinId||CoolClock.config.defaultSkin;
this.showSecondHand=typeof showSecondHand=="boolean"?showSecondHand :true;
this.tickDelay=CoolClock.config[this.showSecondHand?"tickDelay" :"longTickDelay"];
if(_IE)
this.tickDelay=15000;

this.canvas=document.getElementById(canvasId);

this.canvas.setAttribute("width",this.displayRadius*2);
this.canvas.setAttribute("height",this.displayRadius*2);

this.canvas.style.width=this.displayRadius*2+"px";
this.canvas.style.height=this.displayRadius*2+"px";

this.renderRadius=CoolClock.config.renderRadius;

this.scale=this.displayRadius / this.renderRadius;
this.ctx=this.canvas.getContext("2d");
this.ctx.scale(this.scale,this.scale);

this.gmtOffset=gmtOffset!=null?parseFloat(gmtOffset):gmtOffset;

CoolClock.config.clockTracker[canvasId]=this;
this.tick();
return this;
},

fullCircle:function(skin){
this.fullCircleAt(this.renderRadius,this.renderRadius,skin);
},

fullCircleAt:function(x,y,skin){
with (this.ctx){
save();
globalAlpha=skin.alpha;
lineWidth=skin.lineWidth;
if(!document.all)
beginPath();
if(document.all)

lineWidth=lineWidth * this.scale;
arc(x,y,skin.radius,0,2*Math.PI,false);
if(document.all)

arc(x,y,skin.radius,-0.1,0.1,false);
if(skin.fillColor){
fillStyle=skin.fillColor
fill();
}
else{

strokeStyle=skin.color;
stroke();
}
restore();
}
},

radialLineAtAngle:function(angleFraction,skin){
with (this.ctx){
save();
translate(this.renderRadius,this.renderRadius);
rotate(Math.PI * (2 * angleFraction-0.5));
globalAlpha=skin.alpha;
strokeStyle=skin.color;
lineWidth=skin.lineWidth;
if(document.all)

lineWidth=lineWidth * this.scale;
if(skin.radius){
this.fullCircleAt(skin.startAt,0,skin)
}
else{
beginPath();
moveTo(skin.startAt,0)
lineTo(skin.endAt,0);
stroke();
}
restore();
}
},

render:function(hour,min,sec){
var skin=CoolClock.config.skins[this.skinId];
var R=this.renderRadius;
this.ctx.clearRect(0,0,R*2,R*2);

this.ctx.fillStyle="white";

with (this.ctx){
var R=this.renderRadius;

strokeStyle="#ffffff";
for(var i=0;i<2*R;i++){
var v=i<R?(R-i):(i-R);
v=Math.floor(Math.sqrt(R*R-v*v));
beginPath();
moveTo(R-v,i);
lineTo(R+v,i);
stroke();
}
}

this.fullCircle(skin.outerBorder);

for(var i=0;i<60;i++)
this.radialLineAtAngle(i/60,skin[i%5?"smallIndicator" :"largeIndicator"]);

this.radialLineAtAngle((hour+min/60)/12,skin.hourHand);
this.radialLineAtAngle((min+sec/60)/60,skin.minuteHand);
if(this.showSecondHand){
this.radialLineAtAngle(sec/60,skin.secondHand);
if(!document.all){

this.radialLineAtAngle(sec/60,skin.secondDecoration);
}
}
},


nextTick:function(){
setTimeout("CoolClock.config.clockTracker['"+this.canvasId+"'].tick()",this.tickDelay);
},

stillHere:function(){
return document.getElementById(this.canvasId)!=null;
},

refreshDisplay:function(){
var now=new Date();
if(currentTimeDelta){
var nnow=new Date(now.valueOf()-(now.getTimezoneOffset()*60+currentTimeDelta)*1000);
now=nnow;
}
if(this.gmtOffset!=null){

var offsetNow=new Date(now.valueOf()+(this.gmtOffset * 1000 * 60 * 60));
this.render(offsetNow.getUTCHours(),offsetNow.getUTCMinutes(),offsetNow.getUTCSeconds());
}
else{

this.render(now.getHours(),now.getMinutes(),now.getSeconds());
}
},

tick:function(){
if(this.stillHere()){
this.refreshDisplay()
this.nextTick();
}
}
}
